#    Copyright 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
FTPFileName='/opt/coopgis/fromgps/anonymousftproot_OtherReadOnly/incomingftpallpermissions/Locations.csv'
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopgis/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
import djangoproject
from djangoproject.models import *
#********************Setup psycopg2 and django section********************
import COOPGIS_Ajax, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update, COOPGIS_ReportLabStakerReport
import COOPGIS_FormMisc
from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings

def BuildInspectionChoiceForm():
    from django.contrib import admin
    Dict={}
    #Build Inspection Choices List
    InspectionChoices=[]
    EndOfListChoices=[]
    SubstationInspectionChoices=SubstationInspectionChoice.objects.all().order_by('Name')
    for i in SubstationInspectionChoices:
        if(i.ActiveIndicator):
            InspectionChoices.append([i.id, str(i)])
        else:
            EndOfListChoices.append([i.id, 'INACTIVE:  ' + str(i)])
    for i in EndOfListChoices:
        InspectionChoices.append(i)
    Dict['Inspections']=forms.ChoiceField(InspectionChoices, required=False)
    #SubstationInspectionChoice Attribute Fields
    Dict['Name']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['Description']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['SubstationInspectionChoiceid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5', 'READONLY':'True'}))    
    Dict['ActiveIndicator']=forms.BooleanField(required=False)
    #Action Fields
    Dict['UpdateIndicator']=forms.BooleanField(required=False)
    Dict['NewIndicator']=forms.BooleanField(required=False)    
    return Dict

def ProcessInspectionChoiceForm(form, UserName):
    import models
    UpdateIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateIndicator')
    NewIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NewIndicator')
    ActiveIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ActiveIndicator')
    Name=COOPGIS_FormMisc.FormGetString(form, 'Name')
    Description=COOPGIS_FormMisc.FormGetString(form, 'Description')
    SubstationInspectionChoiceid=COOPGIS_FormMisc.FormGetInteger(form, 'Inspections', 0)
    try:
        substationInspectionChoice=SubstationInspectionChoice.objects.filter(id=SubstationInspectionChoiceid)[0]
    except:
        substationInspectionChoice=None
    command=Command()    
    if(NewIndicator):
        command=command.Create(Name='CreateSubstationInspectionChoice', ObjectName=Name, Description=Description, ActiveIndicator=ActiveIndicator,
                               CommandUserName=UserName)
        substationInspectionChoice=command.Process()
    elif(UpdateIndicator and substationInspectionChoice):
        Objectid, ObjectIndexWhenReverseSorted=substationInspectionChoice.GetCommandidData()
        command=command.Create(Name='EditSubstationInspectionChoice', Objectid=substationInspectionChoice.id, ObjectName=Name,
                               Description=Description, ActiveIndicator=ActiveIndicator, CommandUserName=UserName)
        command.Process()
    return substationInspectionChoice

def PopulateInspectionChoiceForm(form, substationInspectionChoice):
    form.data['UpdateIndicator']=False
    form.data['NewIndicator']=False
    if(substationInspectionChoice):
        form.data['Name']=substationInspectionChoice.Name
        form.data['SubstationInspectionChoiceid']=substationInspectionChoice.id
        form.data['Description']=substationInspectionChoice.Description
    else:
        form.data['Name']=''
        form.data['SubstationInspectionChoiceid']=''
        form.data['Description']=''
    return form





def BuildEquipmentModelTypeForm(substationEquipmentModelType):
    from django.contrib import admin
    Dict={}
    #Build EquipmentModelType List
    EquipmentModelTypeChoices=[]
    EquipmentModelTypes=SubstationEquipmentModelType.objects.all().order_by('Name')
    for i in EquipmentModelTypes:
            EquipmentModelTypeChoices.append([i.id, str(i)])
    Dict['EquipmentModelTypeSelection']=forms.ChoiceField(EquipmentModelTypeChoices, required=False)
    ManufacturerChoices=[]
    if(substationEquipmentModelType and substationEquipmentModelType.Manufacturer):
        ManufacturerChoices.append([substationEquipmentModelType.Manufacturer.id, str(substationEquipmentModelType.Manufacturer)])
    ManufacturerChoices.append((-1, 'None Selected'))
    Manufacturers=Company.objects.all().filter(ManufacturerIndicator__exact=True).order_by('Name')
    for i in Manufacturers:
        if(not [i.id, str(i)] in ManufacturerChoices):
            ManufacturerChoices.append([i.id, str(i)])
    Dict['ManufacturerSelection']=forms.ChoiceField(ManufacturerChoices, required=False)
    #EquipmentModelType Attribute Fields
    Dict['Name']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['Description']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['TransformerIndicator']=forms.BooleanField(required=False)
    Dict['RegulatorIndicator']=forms.BooleanField(required=False)
    Dict['RegulatorControllerIndicator']=forms.BooleanField(required=False)
    Dict['TransmissionOverCurrentRelayIndicator']=forms.BooleanField(required=False)
    Dict['EquipmentModelTypeid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5', 'READONLY':'True'}))    
    Dict['RecloserIndicator']=forms.BooleanField(required=False)
    Dict['RecloserControllerIndicator']=forms.BooleanField(required=False)
    Dict['CircuitSwitcherIndicator']=forms.BooleanField(required=False)
    Dict['BatteryBankIndicator']=forms.BooleanField(required=False)
    #Action Fields
    Dict['UpdateIndicator']=forms.BooleanField(required=False)
    Dict['NewIndicator']=forms.BooleanField(required=False)    
    return Dict

def ProcessEquipmentModelTypeForm(form, UserName):
    import models
    UpdateIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateIndicator')
    NewIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NewIndicator')
    Name=COOPGIS_FormMisc.FormGetString(form, 'Name')
    Description=COOPGIS_FormMisc.FormGetString(form, 'Description')
    TransformerIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'TransformerIndicator')
    RegulatorIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'RegulatorIndicator')
    RegulatorControllerIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'RegulatorControllerIndicator')
    TransmissionOverCurrentRelayIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'TransmissionOverCurrentRelayIndicator')
    RecloserIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'RecloserIndicator')
    RecloserControllerIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'RecloserControllerIndicator')
    CircuitSwitcherIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'CircuitSwitcherIndicator')
    BatteryBankIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'BatteryBankIndicator')
    EquipmentModelTypeid=COOPGIS_FormMisc.FormGetInteger(form, 'EquipmentModelTypeSelection', 0)
    try:
        substationEquipmentModelType=SubstationEquipmentModelType.objects.filter(id=EquipmentModelTypeid)[0]
    except:
        substationEquipmentModelType=None
    ManufacturerSelectionid=COOPGIS_FormMisc.FormGetInteger(form, 'ManufacturerSelection', 0)
    try:
        manufacturer=Company.objects.filter(id=ManufacturerSelectionid)[0]
        Manufacturerid, ManufacturerIndexWhenReverseSorted=manufacturer.GetCommandidData()
    except IndexError:
        manufacturer=None
        Manufacturerid, ManufacturerIndexWhenReverseSorted=(-1, -1)
    command=Command()    
    if(NewIndicator):
        command=command.Create(Name='CreateSubstationEquipmentModelType', ObjectName=Name, Description=Description, Manufacturerid=Manufacturerid,
                               ManufacturerIndexWhenReverseSorted=ManufacturerIndexWhenReverseSorted, TransformerIndicator=TransformerIndicator,
                               RegulatorIndicator=RegulatorIndicator, RegulatorControllerIndicator=RegulatorControllerIndicator, 
                               TransmissionOverCurrentRelayIndicator=TransmissionOverCurrentRelayIndicator, 
                               RecloserIndicator=RecloserIndicator, RecloserControllerIndicator=RecloserControllerIndicator,
                               CircuitSwitcherIndicator=CircuitSwitcherIndicator, BatteryBankIndicator=BatteryBankIndicator,
                               CommandUserName=UserName)
        substationEquipmentModelType=command.Process()
    elif(UpdateIndicator and substationEquipmentModelType):
        Objectid, ObjectIndexWhenReverseSorted=substationEquipmentModelType.GetCommandidData()
        command=command.Create(Name='EditSubstationEquipmentModelType', ObjectName=Name, Objectid=Objectid, 
                               ObjectIndexWhenReverseSorted=ObjectIndexWhenReverseSorted,
                               Description=Description, Manufacturerid=Manufacturerid,
                               ManufacturerIndexWhenReverseSorted=ManufacturerIndexWhenReverseSorted, TransformerIndicator=TransformerIndicator,
                               RegulatorIndicator=RegulatorIndicator, RegulatorControllerIndicator=RegulatorControllerIndicator, 
                               TransmissionOverCurrentRelayIndicator=TransmissionOverCurrentRelayIndicator, 
                               RecloserIndicator=RecloserIndicator, RecloserControllerIndicator=RecloserControllerIndicator,
                               CircuitSwitcherIndicator=CircuitSwitcherIndicator, BatteryBankIndicator=BatteryBankIndicator,
                               CommandUserName=UserName)
        substationEquipmentModelType=command.Process()
    return substationEquipmentModelType

def PopulateEquipmentModelTypeForm(form, equipmentModelType):
    form.data['UpdateIndicator']=False
    form.data['NewIndicator']=False
    if(equipmentModelType):
        form.data['Name']=equipmentModelType.Name
        form.data['EquipmentModelTypeid']=equipmentModelType.id
        form.data['Description']=equipmentModelType.Description
        form.data['TransformerIndicator']=equipmentModelType.TransformerIndicator
        form.data['RegulatorIndicator']=equipmentModelType.RegulatorIndicator
        form.data['RegulatorControllerIndicator']=equipmentModelType.RegulatorControllerIndicator
        form.data['TransmissionOverCurrentRelayIndicator']=equipmentModelType.TransmissionOverCurrentRelayIndicator
        form.data['RecloserIndicator=RecloserIndicator']=equipmentModelType.RecloserIndicator
        form.data['RecloserControllerIndicator']=equipmentModelType.RecloserControllerIndicator
        form.data['CircuitSwitcherIndicator']=equipmentModelType.CircuitSwitcherIndicator
        form.data['BatteryBankIndicator']=equipmentModelType.BatteryBankIndicator
        if(equipmentModelType.Manufacturer):
            form.setData({'ManufacturerSelection': equipmentModelType.Manufacturer.id})
        else:
            form.setData({'ManufacturerSelection': -1})
    else:
        form.data['Name']=''
        form.data['EquipmentModelTypeid']=''
        form.data['Description']=''
        form.data['TransformerIndicator']=False
        form.data['RegulatorIndicator']=False
        form.data['RegulatorControllerIndicator']=False
        form.data['TransmissionOverCurrentRelayIndicator']=False
        form.data['RecloserIndicator=RecloserIndicator']=False
        form.data['RecloserControllerIndicator']=False
        form.data['CircuitSwitcherIndicator']=False
        form.data['BatteryBankIndicator']=False
        form.setData({'ManufacturerSelection': -1})
    return form



def BuildSubstationSetupForm(substation):
    from django.contrib import admin
    Dict={}
    SubstationChoices=[]
    if(substation):
        SubstationChoices.append([substation.id, str(substation)])
    SubstationChoices.append((-1, 'None Selected'))
    Substations=Substation.objects.all().order_by('Name')
    for i in Substations:
        if(not [i.id, str(i)] in SubstationChoices):
            SubstationChoices.append([i.id, str(i)])
    Dict['SubstationSelection']=forms.ChoiceField(SubstationChoices, required=False)
    Dict['Name']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['Description']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['Assemblyid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['ActiveIndicator']=forms.BooleanField(required=False)
    Dict['Substationid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5', 'READONLY':'True'}))    
    #Action Fields
    Dict['UpdateIndicator']=forms.BooleanField(required=False)
    Dict['NewIndicator']=forms.BooleanField(required=False)    
    return Dict


def ProcessSubstationSetupForm(form, UserName):
    import models
    UpdateIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateIndicator')
    NewIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NewIndicator')
    Name=COOPGIS_FormMisc.FormGetString(form, 'Name')
    Description=COOPGIS_FormMisc.FormGetString(form, 'Description')
    AssemblySelectionid=COOPGIS_FormMisc.FormGetInteger(form, 'Assemblyid')
    Substationid=COOPGIS_FormMisc.FormGetInteger(form, 'SubstationSelection')

    try:
        substation=Substation.objects.filter(id=Substationid)[0]
    except:
        substation=None
    if(substation and not NewIndicator and not UpdateIndicator):
        if(substation.Assembly):
            AssemblySelectionid=substation.Assembly.id
        else:
            AssemblySelectionid=None
    try:
        assembly=Assembly.objects.filter(id=AssemblySelectionid)[0]
        Assemblyid, AssemblyIndexWhenReverseSorted=assembly.GetCommandidData()
    except:
        assembly=None
        Assemblyid, AssemblyIndexWhenReverseSorted=(-1, -1)
    ActiveIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ActiveIndicator')
    command=Command()    



    if(NewIndicator):
        command=command.Create(Name='CreateSubstation', ObjectName=Name, Description=Description, Assemblyid=Assemblyid, 
                               AssemblyIndexWhenReverseSorted=AssemblyIndexWhenReverseSorted, ActiveIndicator=ActiveIndicator,
                               CommandUserName=UserName)
        substation=command.Process()
    elif(UpdateIndicator and COOPGIS_FormMisc.FormGetInteger(form, 'Substationid')):
        Substationid=COOPGIS_FormMisc.FormGetInteger(form, 'Substationid')
        substation=Substation.objects.filter(id=Substationid)[0]
        Objectid, ObjectIndexWhenReverseSorted=substation.GetCommandidData()
        command=command.Create(Name='EditSubstation', ObjectName=Name, Objectid=Objectid, ObjectIndexWhenReverseSorted=ObjectIndexWhenReverseSorted,
                               Description=Description, Assemblyid=Assemblyid, AssemblyIndexWhenReverseSorted=AssemblyIndexWhenReverseSorted, 
                               ActiveIndicator=ActiveIndicator, CommandUserName=UserName)
        substation=command.Process()
    return substation

def PopulateSubstationSetupForm(form, substation):
    form.data['UpdateIndicator']=False
    form.data['NewIndicator']=False
    if(substation):
        form.data['Name']=substation.Name
        form.data['Substationid']=substation.id
        form.data['Description']=substation.Description
        form.data['ActiveIndicator']=substation.ActiveIndicator
        if(substation.Assembly):
            form.data['Assemblyid']=substation.Assembly.id
        else:
            form.data['Assemblyid']=''
    else:
        form.data['Name']=''
        form.data['Substationid']=''
        form.data['Description']=''
        form.data['Assemblyid']=''
        form.data['ActiveIndicator']=False

    return form



def BuildSubstationEquipmentTemplateForm(equipmentTemplate):
    from django.contrib import admin
    Dict={}
    EquipmentTemplateChoices=[]
    if(equipmentTemplate):
        EquipmentTemplateChoices.append([equipmentTemplate.id, str(equipmentTemplate)])
    EquipmentTemplateChoices.append((-1, 'None Selected'))
    EquipmentTemplates=SubstationEquipmentTemplate.objects.all().order_by('Name')
    for i in EquipmentTemplates:
        if(not [i.id, str(i)] in EquipmentTemplateChoices):
            EquipmentTemplateChoices.append([i.id, str(i)])
    Dict['EquipmentTemplateSelection']=forms.ChoiceField(EquipmentTemplateChoices, required=False)
    Dict['Name']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['SubstationEquipmentTemplateid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5', 'READONLY':'True'}))    
    Dict['DescriptionOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['BatteryTestOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['BatteryVoltageNormalOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['BatteryVoltageTestOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['BatteryChargeOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['BatteryVisualOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['GroundOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['VisualOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['MeterKWHOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['MeterKWOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserAmperageAOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserAmperageBOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserAmperageCOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserAmperageGroundOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserMaxDemandAOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserMaxDemandBOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserMaxDemandCOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserMaxDemandGroundOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserOperationCounterOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserOperationSummaryAOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserOperationSummaryBOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserOperationSummaryCOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserTargetAOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserTargetBOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserTargetCOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserTargetGroundOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RegulatorDragHandPositionMinimumOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RegulatorDragHandPositionCurrentOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RegulatorDragHandPositionMaximumOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RegulatorVoltCurrentOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RegulatorVoltLowOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RegulatorVoltHighOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RegulatorMaxAmpOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['SurgeProtectorVisualOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['TransformerOilLeakOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['TransformerOilLevelOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['TransformerOilTemperatureMaximumOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['TransformerOilTemperatureCurrentOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['TransformerNitrogenPressureOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['TransformerOilVisualOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['TransformerWindingTemperatureMaximumOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['TransformerWindingTemperatureCurrentOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['MechanismChargeOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['OperationCounterOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['FanWorkingVisualOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['DemandAmpAOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['DemandAmpBOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['DemandAmpCOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['OverCurrentTripOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['BreakerCounterOrder']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['ActiveIndicator']=forms.BooleanField(required=False)
    #Action Fields
    Dict['UpdateIndicator']=forms.BooleanField(required=False)
    Dict['NewIndicator']=forms.BooleanField(required=False)    
    return Dict





def ProcessSubstationEquipmentTemplateForm(form, UserName):
    import models
    UpdateIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateIndicator')
    NewIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NewIndicator')
    Name=COOPGIS_FormMisc.FormGetString(form, 'Name')
    DescriptionOrder=COOPGIS_FormMisc.FormGetFloat(form, 'DescriptionOrder')
    BatteryTestOrder=COOPGIS_FormMisc.FormGetFloat(form, 'BatteryTestOrder')
    BatteryVoltageNormalOrder=COOPGIS_FormMisc.FormGetFloat(form, 'BatteryVoltageNormalOrder')
    BatteryVoltageTestOrder=COOPGIS_FormMisc.FormGetFloat(form, 'BatteryVoltageTestOrder')
    BatteryChargeOrder=COOPGIS_FormMisc.FormGetFloat(form, 'BatteryChargeOrder')
    BatteryVisualOrder=COOPGIS_FormMisc.FormGetFloat(form, 'BatteryVisualOrder')
    GroundOrder=COOPGIS_FormMisc.FormGetFloat(form, 'GroundOrder')
    VisualOrder=COOPGIS_FormMisc.FormGetFloat(form, 'VisualOrder')
    MeterKWHOrder=COOPGIS_FormMisc.FormGetFloat(form, 'MeterKWHOrder')
    MeterKWOrder=COOPGIS_FormMisc.FormGetFloat(form, 'MeterKWOrder')
    RecloserAmperageAOrder=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserAmperageAOrder')
    RecloserAmperageBOrder=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserAmperageBOrder')
    RecloserAmperageCOrder=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserAmperageCOrder')
    RecloserAmperageGroundOrder=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserAmperageGroundOrder')
    RecloserMaxDemandAOrder=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserMaxDemandAOrder')
    RecloserMaxDemandBOrder=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserMaxDemandBOrder')
    RecloserMaxDemandCOrder=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserMaxDemandCOrder')
    RecloserMaxDemandGroundOrder=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserMaxDemandGroundOrder')
    RecloserOperationCounterOrder=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserOperationCounterOrder')
    RecloserOperationSummaryAOrder=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserOperationSummaryAOrder')
    RecloserOperationSummaryBOrder=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserOperationSummaryBOrder')
    RecloserOperationSummaryCOrder=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserOperationSummaryCOrder') 
    RecloserTargetAOrder=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserTargetAOrder')
    RecloserTargetBOrder=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserTargetBOrder')
    RecloserTargetCOrder=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserTargetCOrder')
    RecloserTargetGroundOrder=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserTargetGroundOrder')
    RegulatorDragHandPositionMinimumOrder=COOPGIS_FormMisc.FormGetFloat(form, 'RegulatorDragHandPositionMinimumOrder')
    RegulatorDragHandPositionCurrentOrder=COOPGIS_FormMisc.FormGetFloat(form, 'RegulatorDragHandPositionCurrentOrder')
    RegulatorDragHandPositionMaximumOrder=COOPGIS_FormMisc.FormGetFloat(form, 'RegulatorDragHandPositionMaximumOrder')
    RegulatorVoltCurrentOrder=COOPGIS_FormMisc.FormGetFloat(form, 'RegulatorVoltCurrentOrder')
    RegulatorVoltLowOrder=COOPGIS_FormMisc.FormGetFloat(form, 'RegulatorVoltLowOrder')
    RegulatorVoltHighOrder=COOPGIS_FormMisc.FormGetFloat(form, 'RegulatorVoltHighOrder')
    RegulatorMaxAmpOrder=COOPGIS_FormMisc.FormGetFloat(form, 'RegulatorMaxAmpOrder')
    SurgeProtectorVisualOrder=COOPGIS_FormMisc.FormGetFloat(form, 'SurgeProtectorVisualOrder')
    TransformerOilLeakOrder=COOPGIS_FormMisc.FormGetFloat(form, 'TransformerOilLeakOrder')
    TransformerOilLevelOrder=COOPGIS_FormMisc.FormGetFloat(form, 'TransformerOilLevelOrder')
    TransformerOilTemperatureMaximumOrder=COOPGIS_FormMisc.FormGetFloat(form, 'TransformerOilTemperatureMaximumOrder')
    TransformerOilTemperatureCurrentOrder=COOPGIS_FormMisc.FormGetFloat(form, 'TransformerOilTemperatureCurrentOrder')
    TransformerNitrogenPressureOrder=COOPGIS_FormMisc.FormGetFloat(form, 'TransformerNitrogenPressureOrder')
    TransformerOilVisualOrder=COOPGIS_FormMisc.FormGetFloat(form, 'TransformerOilVisualOrder')
    TransformerWindingTemperatureCurrentOrder=COOPGIS_FormMisc.FormGetFloat(form, 'TransformerWindingTemperatureCurrentOrder')
    TransformerWindingTemperatureMaximumOrder=COOPGIS_FormMisc.FormGetFloat(form, 'TransformerWindingTemperatureMaximumOrder')
    MechanismChargeOrder=COOPGIS_FormMisc.FormGetFloat(form, 'MechanismChargeOrder')
    OperationCounterOrder=COOPGIS_FormMisc.FormGetFloat(form, 'OperationCounterOrder')
    FanWorkingVisualOrder=COOPGIS_FormMisc.FormGetFloat(form, 'FanWorkingVisualOrder')
    ActiveIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ActiveIndicator') 
    SubstationEquipmentTemplateSelectionid=COOPGIS_FormMisc.FormGetInteger(form, 'EquipmentTemplateSelection')
    DemandAmpAOrder=COOPGIS_FormMisc.FormGetFloat(form, 'DemandAmpAOrder')
    DemandAmpBOrder=COOPGIS_FormMisc.FormGetFloat(form, 'DemandAmpBOrder')
    DemandAmpCOrder=COOPGIS_FormMisc.FormGetFloat(form, 'DemandAmpCOrder')
    OverCurrentTripOrder=COOPGIS_FormMisc.FormGetFloat(form, 'OverCurrentTripOrder')
    BreakerCounterOrder=COOPGIS_FormMisc.FormGetFloat(form, 'BreakerCounterOrder')



    try:
        substationEquipmentTemplate=SubstationEquipmentTemplate.objects.filter(id=SubstationEquipmentTemplateSelectionid)[0]
    except:
        substationEquipmentTemplate=None
    command=Command()
    if(NewIndicator):
        command=command.Create(Name='CreateSubstationEquipmentTemplate', ObjectName=Name, DescriptionOrder=DescriptionOrder, BatteryTestOrder=BatteryTestOrder,
                               BatteryVoltageTestOrder=BatteryVoltageTestOrder, BatteryVoltageNormalOrder=BatteryVoltageNormalOrder, 
                               BatteryChargeOrder=BatteryChargeOrder,
                               BatteryVisualOrder=BatteryVisualOrder, GroundOrder=GroundOrder, VisualOrder=VisualOrder, 
                               MeterKWHOrder=MeterKWHOrder, MeterKWOrder=MeterKWOrder, 
                               RecloserAmperageAOrder=RecloserAmperageAOrder, RecloserAmperageBOrder=RecloserAmperageBOrder, 
                               RecloserAmperageCOrder=RecloserAmperageCOrder, RecloserAmperageGroundOrder=RecloserAmperageGroundOrder, 
                               RecloserMaxDemandAOrder=RecloserMaxDemandAOrder, RecloserMaxDemandBOrder=RecloserMaxDemandBOrder, 
                               RecloserMaxDemandCOrder=RecloserMaxDemandCOrder, RecloserMaxDemandGroundOrder=RecloserMaxDemandGroundOrder, 
                               RecloserOperationCounterOrder=RecloserOperationCounterOrder, RecloserOperationSummaryAOrder=RecloserOperationSummaryAOrder,
                               RecloserOperationSummaryBOrder=RecloserOperationSummaryBOrder, RecloserOperationSummaryCOrder=RecloserOperationSummaryCOrder, 
                               RecloserTargetAOrder=RecloserTargetAOrder, RecloserTargetBOrder=RecloserTargetBOrder, RecloserTargetCOrder=RecloserTargetCOrder, 
                               RecloserTargetGroundOrder=RecloserTargetGroundOrder, RegulatorDragHandPositionMinimumOrder=RegulatorDragHandPositionMinimumOrder, 
                               RegulatorDragHandPositionCurrentOrder=RegulatorDragHandPositionCurrentOrder,
                               RegulatorDragHandPositionMaximumOrder=RegulatorDragHandPositionMaximumOrder, RegulatorVoltCurrentOrder=RegulatorVoltCurrentOrder, 
                               RegulatorVoltLowOrder=RegulatorVoltLowOrder, RegulatorVoltHighOrder=RegulatorVoltHighOrder,
                               RegulatorMaxAmpOrder=RegulatorMaxAmpOrder,  
                               SurgeProtectorVisualOrder=SurgeProtectorVisualOrder, 
                               TransformerOilLeakOrder=TransformerOilLeakOrder, TransformerOilLevelOrder=TransformerOilLevelOrder, 
                               TransformerOilTemperatureMaximumOrder=TransformerOilTemperatureMaximumOrder, 
                               TransformerOilTemperatureCurrentOrder=TransformerOilTemperatureCurrentOrder, 
                               TransformerNitrogenPressureOrder=TransformerNitrogenPressureOrder, TransformerOilVisualOrder=TransformerOilVisualOrder, 
                               TransformerWindingTemperatureMaximumOrder=TransformerWindingTemperatureMaximumOrder,
                               TransformerWindingTemperatureCurrentOrder=TransformerWindingTemperatureCurrentOrder,
                               MechanismChargeOrder=MechanismChargeOrder, OperationCounterOrder=OperationCounterOrder,
                               FanWorkingVisualOrder=FanWorkingVisualOrder,
                               ActiveIndicator=ActiveIndicator, DemandAmpAOrder=DemandAmpAOrder, DemandAmpBOrder=DemandAmpBOrder,
                               DemandAmpCOrder=DemandAmpCOrder, OverCurrentTripOrder=OverCurrentTripOrder, BreakerCounterOrder=BreakerCounterOrder,
                               CommandUserName=UserName)
        substationEquipmentTemplate=command.Process()
    elif(UpdateIndicator and COOPGIS_FormMisc.FormGetInteger(form, 'SubstationEquipmentTemplateid')):
        SubstationEquipmentTemplateid=COOPGIS_FormMisc.FormGetInteger(form, 'SubstationEquipmentTemplateid')
        substationEquipmentTemplate=SubstationEquipmentTemplate.objects.filter(id=SubstationEquipmentTemplateid)[0]
        Objectid, ObjectIndexWhenReverseSorted=substationEquipmentTemplate.GetCommandidData()
        command=command.Create(Name='EditSubstationEquipmentTemplate', ObjectName=Name, Objectid=Objectid, 
                               ObjectIndexWhenReverseSorted=ObjectIndexWhenReverseSorted,
                               DescriptionOrder=DescriptionOrder, BatteryTestOrder=BatteryTestOrder,
                               BatteryVoltageTestOrder=BatteryVoltageTestOrder, BatteryVoltageNormalOrder=BatteryVoltageNormalOrder, 
                               BatteryChargeOrder=BatteryChargeOrder,
                               BatteryVisualOrder=BatteryVisualOrder, GroundOrder=GroundOrder, VisualOrder=VisualOrder, 
                               MeterKWHOrder=MeterKWHOrder, MeterKWOrder=MeterKWOrder, 
                               RecloserAmperageAOrder=RecloserAmperageAOrder, RecloserAmperageBOrder=RecloserAmperageBOrder, 
                               RecloserAmperageCOrder=RecloserAmperageCOrder, RecloserAmperageGroundOrder=RecloserAmperageGroundOrder, 
                               RecloserMaxDemandAOrder=RecloserMaxDemandAOrder, RecloserMaxDemandBOrder=RecloserMaxDemandBOrder, 
                               RecloserMaxDemandCOrder=RecloserMaxDemandCOrder, RecloserMaxDemandGroundOrder=RecloserMaxDemandGroundOrder, 
                               RecloserOperationCounterOrder=RecloserOperationCounterOrder, RecloserOperationSummaryAOrder=RecloserOperationSummaryAOrder,
                               RecloserOperationSummaryBOrder=RecloserOperationSummaryBOrder, RecloserOperationSummaryCOrder=RecloserOperationSummaryCOrder, 
                               RecloserTargetAOrder=RecloserTargetAOrder, RecloserTargetBOrder=RecloserTargetBOrder, RecloserTargetCOrder=RecloserTargetCOrder, 
                               RecloserTargetGroundOrder=RecloserTargetGroundOrder, 
                               RegulatorDragHandPositionMinimumOrder=RegulatorDragHandPositionMinimumOrder, 
                               RegulatorDragHandPositionCurrentOrder=RegulatorDragHandPositionCurrentOrder,
                               RegulatorDragHandPositionMaximumOrder=RegulatorDragHandPositionMaximumOrder,
                               RegulatorVoltCurrentOrder=RegulatorVoltCurrentOrder, 
                               RegulatorVoltLowOrder=RegulatorVoltLowOrder, RegulatorVoltHighOrder=RegulatorVoltHighOrder,
                               RegulatorMaxAmpOrder=RegulatorMaxAmpOrder,  
                               SurgeProtectorVisualOrder=SurgeProtectorVisualOrder, 
                               TransformerOilLeakOrder=TransformerOilLeakOrder, TransformerOilLevelOrder=TransformerOilLevelOrder, 
                               TransformerOilTemperatureCurrentOrder=TransformerOilTemperatureCurrentOrder, 
                               TransformerOilTemperatureMaximumOrder=TransformerOilTemperatureMaximumOrder, 
                               TransformerNitrogenPressureOrder=TransformerNitrogenPressureOrder, TransformerOilVisualOrder=TransformerOilVisualOrder, 
                               TransformerWindingTemperatureMaximumOrder=TransformerWindingTemperatureMaximumOrder,
                               TransformerWindingTemperatureCurrentOrder=TransformerWindingTemperatureCurrentOrder,
                               MechanismChargeOrder=MechanismChargeOrder, OperationCounterOrder=OperationCounterOrder,
                               FanWorkingVisualOrder=FanWorkingVisualOrder, ActiveIndicator=ActiveIndicator,
                               DemandAmpAOrder=DemandAmpAOrder, DemandAmpBOrder=DemandAmpBOrder,
                               DemandAmpCOrder=DemandAmpCOrder, OverCurrentTripOrder=OverCurrentTripOrder, BreakerCounterOrder=BreakerCounterOrder,
                               CommandUserName=UserName)
        substationEquipmentTemplate=command.Process()
    return substationEquipmentTemplate

def PopulateSubstationEquipmentTemplateForm(form, substationEquipmentTemplate):
    form.data['UpdateIndicator']=False
    form.data['NewIndicator']=False
    if(substationEquipmentTemplate):
        form.data['Name']=substationEquipmentTemplate.Name
        form.data['SubstationEquipmentTemplateid']=substationEquipmentTemplate.id
        form.data['DescriptionOrder']=substationEquipmentTemplate.DescriptionOrder
        form.data['BatteryTestOrder']=substationEquipmentTemplate.BatteryTestOrder
        form.data['BatteryVoltageTestOrder']=substationEquipmentTemplate.BatteryVoltageTestOrder
        form.data['BatteryVoltageNormalOrder']=substationEquipmentTemplate.BatteryVoltageNormalOrder
        form.data['BatteryChargeOrder']=substationEquipmentTemplate.BatteryChargeOrder
        form.data['BatteryVisualOrder']=substationEquipmentTemplate.BatteryVisualOrder
        form.data['GroundOrder']=substationEquipmentTemplate.GroundOrder
        form.data['VisualOrder']=substationEquipmentTemplate.VisualOrder
        form.data['MeterKWHOrder']=substationEquipmentTemplate.MeterKWHOrder
        form.data['MeterKWOrder']=substationEquipmentTemplate.MeterKWOrder
        form.data['RecloserAmperageAOrder']=substationEquipmentTemplate.RecloserAmperageAOrder
        form.data['RecloserAmperageBOrder']=substationEquipmentTemplate.RecloserAmperageBOrder
        form.data['RecloserAmperageCOrder']=substationEquipmentTemplate.RecloserAmperageCOrder
        form.data['RecloserAmperageGroundOrder']=substationEquipmentTemplate.RecloserAmperageGroundOrder
        form.data['RecloserMaxDemandAOrder']=substationEquipmentTemplate.RecloserMaxDemandAOrder
        form.data['RecloserMaxDemandBOrder']=substationEquipmentTemplate.RecloserMaxDemandBOrder
        form.data['RecloserMaxDemandCOrder']=substationEquipmentTemplate.RecloserMaxDemandCOrder
        form.data['RecloserMaxDemandGroundOrder']=substationEquipmentTemplate.RecloserMaxDemandGroundOrder
        form.data['RecloserOperationCounterOrder']=substationEquipmentTemplate.RecloserOperationCounterOrder
        form.data['RecloserOperationSummaryAOrder']=substationEquipmentTemplate.RecloserOperationSummaryAOrder
        form.data['RecloserOperationSummaryBOrder']=substationEquipmentTemplate.RecloserOperationSummaryBOrder
        form.data['RecloserOperationSummaryCOrder']=substationEquipmentTemplate.RecloserOperationSummaryCOrder 
        form.data['RecloserTargetAOrder']=substationEquipmentTemplate.RecloserTargetAOrder
        form.data['RecloserTargetBOrder']=substationEquipmentTemplate.RecloserTargetBOrder
        form.data['RecloserTargetCOrder']=substationEquipmentTemplate.RecloserTargetCOrder
        form.data['RecloserTargetGroundOrder']=substationEquipmentTemplate.RecloserTargetGroundOrder
        form.data['RegulatorDragHandPositionMinimumOrder']=substationEquipmentTemplate.RegulatorDragHandPositionMinimumOrder
        form.data['RegulatorDragHandPositionCurrentOrder']=substationEquipmentTemplate.RegulatorDragHandPositionCurrentOrder
        form.data['RegulatorDragHandPositionMaximumOrder']=substationEquipmentTemplate.RegulatorDragHandPositionMaximumOrder
        form.data['RegulatorVoltCurrentOrder']=substationEquipmentTemplate.RegulatorVoltCurrentOrder
        form.data['RegulatorVoltLowOrder']=substationEquipmentTemplate.RegulatorVoltLowOrder
        form.data['RegulatorVoltHighOrder']=substationEquipmentTemplate.RegulatorVoltHighOrder
        form.data['RegulatorMaxAmpOrder']=substationEquipmentTemplate.RegulatorMaxAmpOrder
        form.data['SurgeProtectorVisualOrder']=substationEquipmentTemplate.SurgeProtectorVisualOrder
        form.data['TransformerOilLeakOrder']=substationEquipmentTemplate.TransformerOilLeakOrder
        form.data['TransformerOilLevelOrder']=substationEquipmentTemplate.TransformerOilLevelOrder
        form.data['TransformerOilTemperatureCurrentOrder']=substationEquipmentTemplate.TransformerOilTemperatureCurrentOrder
        form.data['TransformerOilTemperatureMaximumOrder']=substationEquipmentTemplate.TransformerOilTemperatureMaximumOrder
        form.data['TransformerNitrogenPressureOrder']=substationEquipmentTemplate.TransformerNitrogenPressureOrder
        form.data['TransformerOilVisualOrder']=substationEquipmentTemplate.TransformerOilVisualOrder
        form.data['TransformerWindingTemperatureCurrentOrder']=substationEquipmentTemplate.TransformerWindingTemperatureCurrentOrder
        form.data['TransformerWindingTemperatureMaximumOrder']=substationEquipmentTemplate.TransformerWindingTemperatureMaximumOrder
        form.data['MechanismChargeOrder']=substationEquipmentTemplate.MechanismChargeOrder
        form.data['OperationCounterOrder']=substationEquipmentTemplate.OperationCounterOrder
        form.data['FanWorkingVisualOrder']=substationEquipmentTemplate.FanWorkingVisualOrder
        form.data['DemandAmpAOrder']=substationEquipmentTemplate.DemandAmpAOrder
        form.data['DemandAmpBOrder']=substationEquipmentTemplate.DemandAmpBOrder
        form.data['DemandAmpCOrder']=substationEquipmentTemplate.DemandAmpCOrder
        form.data['OverCurrentTripOrder']=substationEquipmentTemplate.OverCurrentTripOrder
        form.data['BreakerCounterOrder']=substationEquipmentTemplate.BreakerCounterOrder
        form.data['ActiveIndicator']=substationEquipmentTemplate.ActiveIndicator   
    else:
        form.data['Name']=''
        form.data['SubstationEquipmentTemplateid']=''
        form.data['DescriptionOrder']=''
        form.data['BatteryTestOrder']=''
        form.data['BatteryVoltageTestOrder']=''
        form.data['BatteryVoltageNormalOrder']=''
        form.data['BatteryChargeOrder']=''
        form.data['BatteryVisualOrder']=''
        form.data['GroundOrder']=''
        form.data['VisualOrder']=''
        form.data['MeterKWHOrder']=''
        form.data['MeterKWOrder']=''
        form.data['RecloserAmperageAOrder']=''
        form.data['RecloserAmperageBOrder']=''
        form.data['RecloserAmperageCOrder']=''
        form.data['RecloserAmperageGroundOrder']=''
        form.data['RecloserMaxDemandAOrder']=''
        form.data['RecloserMaxDemandBOrder']=''
        form.data['RecloserMaxDemandCOrder']=''
        form.data['RecloserMaxDemandGroundOrder']=''
        form.data['RecloserOperationCounterOrder']=''
        form.data['RecloserOperationSummaryAOrder']=''
        form.data['RecloserOperationSummaryBOrder']=''
        form.data['RecloserOperationSummaryCOrder']='' 
        form.data['RecloserTargetAOrder']=''
        form.data['RecloserTargetBOrder']=''
        form.data['RecloserTargetCOrder']=''
        form.data['RecloserTargetGroundOrder']=''
        form.data['RegulatorDragHandPositionMinimumOrder']=''
        form.data['RegulatorDragHandPositionCurrentOrder']=''
        form.data['RegulatorDragHandPositionMaximumOrder']=''
        form.data['RegulatorVoltCurrentOrder']=''
        form.data['RegulatorVoltLowOrder']=''
        form.data['RegulatorVoltHighOrder']=''
        form.data['RegulatorMaxAmpOrder']=''
        form.data['SurgeProtectorVisualOrder']=''
        form.data['TransformerOilLeakOrder']=''
        form.data['TransformerOilLevelOrder']=''
        form.data['TransformerOilTemperatureMaximumOrder']=''
        form.data['TransformerOilTemperatureCurrentOrder']=''
        form.data['TransformerNitrogenPressureOrder']=''
        form.data['TransformerOilVisualOrder']=''
        form.data['TransformerWindingTemperatureOrder']=''
        form.data['TransformerWindingTemperatureCurrentOrder']=''
        form.data['TransformerWindingTemperatureMaximumOrder']=''
        form.data['MechanismChargeOrder']=''
        form.data['OperationCounterOrder']=''
        form.data['FanWorkingVisualOrder']=''
        form.data['DemandAmpAOrder']=''
        form.data['DemandAmpBOrder']=''
        form.data['DemandAmpCOrder']=''
        form.data['OverCurrentTripOrder']=''
        form.data['BreakerCounterOrder']=''
        form.data['ActiveIndicator']='' 
    return form

def GetTransmissionVoltageChoices(default=None):
    VoltageChoices=[]
    if(default):
        VoltageChoices.append([default.id, str(default)])
    VoltageChoices.append((-1, 'None Selected'))
    Voltages=Voltage.objects.filter(TransmissionIndicator=True).order_by('Name')
    for i in Voltages:
        if(not [i.id, str(i)] in VoltageChoices):
            VoltageChoices.append([i.id, str(i)])
    return VoltageChoices

def GetDistributionVoltageChoices(default=None):
    VoltageChoices=[]
    if(default):
        VoltageChoices.append([default.id, str(default)])
    VoltageChoices.append((-1, 'None Selected'))
    Voltages=Voltage.objects.filter(PrimaryIndicator=True).order_by('Name')
    for i in Voltages:
        if(not [i.id, str(i)] in VoltageChoices):
            VoltageChoices.append([i.id, str(i)])
    return VoltageChoices

def GetSecondaryVoltageChoices(default=None):
    VoltageChoices=[]
    if(default):
        VoltageChoices.append([default.id, str(default)])
    VoltageChoices.append((-1, 'None Selected'))
    Voltages=Voltage.objects.filter(SecondaryIndicator=True).order_by('Name')
    for i in Voltages:
        if(not [i.id, str(i)] in VoltageChoices):
            VoltageChoices.append([i.id, str(i)])
    return VoltageChoices

def GetServiceVoltageChoices(default=None):
    VoltageChoices=[]
    if(default):
        VoltageChoices.append([default.id, str(default)])
    VoltageChoices.append((-1, 'None Selected'))
    Voltages=Voltage.objects.filter(ServiceIndicator=True).order_by('Name')
    for i in Voltages:
        if(not [i.id, str(i)] in VoltageChoices):
            VoltageChoices.append([i.id, str(i)])
    return VoltageChoices

def GetManufacturerChoices(default=None):
    ManufacturerChoices=[]
    if(default):
        ManufacturerChoices.append([default.id, str(default)])
    ManufacturerChoices.append((-1, 'None Selected'))
    Manufacturers=Company.objects.filter(ManufacturerIndicator=True).order_by('Name')
    for i in Manufacturers:
        if(not [i.id, str(i)] in ManufacturerChoices):
            ManufacturerChoices.append([i.id, str(i)])
    return ManufacturerChoices

def GetSubstationEquipmentModelTypeChoices(default=None):
    SubstationEquipmentModelTypeChoices=[]
    if(default):
        SubstationEquipmentModelTypeChoices.append([default.id, str(default)])
    SubstationEquipmentModelTypeChoices.append((-1, 'None Selected'))
    SubstationEquipmentModelTypes=SubstationEquipmentModelType.objects.all().order_by('Name')
    for i in SubstationEquipmentModelTypes:
        if(not [i.id, str(i)] in SubstationEquipmentModelTypeChoices):
            SubstationEquipmentModelTypeChoices.append([i.id, str(i)])
    return SubstationEquipmentModelTypeChoices

def GetSubstationEquipmentTemplateChoices(default=None):
    SubstationEquipmentTemplateChoices=[]
    if(default):
        SubstationEquipmentTemplateChoices.append([default.id, str(default)])
    SubstationEquipmentTemplateChoices.append((-1, 'None Selected'))
    SubstationEquipmentTemplates=SubstationEquipmentTemplate.objects.all().order_by('Name')
    for i in SubstationEquipmentTemplates:
        if(not [i.id, str(i)] in SubstationEquipmentTemplateChoices):
            SubstationEquipmentTemplateChoices.append([i.id, str(i)])
    return SubstationEquipmentTemplateChoices

def GetSubstationChoices(default=None):
    SubstationChoices=[]
    if(default):
        SubstationChoices.append([default.id, str(default)])
    SubstationChoices.append((-1, 'None Selected'))
    Substations=Substation.objects.all().order_by('Name')
    for i in Substations:
        if(not [i.id, str(i)] in SubstationChoices):
            SubstationChoices.append([i.id, str(i)])
    return SubstationChoices

def GetSubstationEquipmentSettingChoices(default=None):
    SubstationEquipmentSettingChoices=[]
    if(default):
        SubstationEquipmentSettingChoices.append([default.id, str(default)])
    SubstationEquipmentSettingChoices.append((-1, 'None Selected'))
    SubstationEquipmentSettings=SubstationEquipmentSetting.objects.all().order_by('Name')
    for i in SubstationEquipmentSettings:
        if(not [i.id, str(i)] in SubstationEquipmentSettingChoices):
            SubstationEquipmentSettingChoices.append([i.id, str(i)])
    return SubstationEquipmentSettingChoices


def GetSubstationCircuitChoices(default=None):
    SubstationCircuitChoices=[]
    if(default):
        SubstationCircuitChoices.append([default.id, str(default)])
    SubstationCircuitChoices.append((-1, 'None Selected'))
    SubstationCircuits=SubstationCircuit.objects.all().order_by('Name')
    for i in SubstationCircuits:
        if(not [i.id, str(i)] in SubstationCircuitChoices):
            SubstationCircuitChoices.append([i.id, str(i)])
    return SubstationCircuitChoices





def BuildSubstationEquipmentForm(substationEquipment):
    from django.contrib import admin
    Dict={}
    SubstationEquipmentChoices=[]
    if(substationEquipment):
        SubstationEquipmentChoices.append([substationEquipment.id, substationEquipment.Name])
    SubstationEquipmentChoices.append((-1, 'None Selected'))
    SubstationEquipments=SubstationEquipment.objects.all().order_by('id')
    for i in SubstationEquipments:
        if(not [i.id, i.Name] in SubstationEquipmentChoices): 
            SubstationEquipmentChoices.append([i.id, i.Name])
    Dict['SubstationEquipmentSelection']=forms.ChoiceField(SubstationEquipmentChoices, required=False)
    TransmissionVoltageChoices=[]
    if(not substationEquipment):
        substationEquipment=SubstationEquipment()
    if(substationEquipment):
        substation=substationEquipment.GetSubstation()
    else:
        substation=None
    Dict['Substation']=forms.ChoiceField(GetSubstationChoices(substation), required=False)
    Dict['SubstationEquipmentName']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'40'}))
    Dict['SubstationEquipmentModelType']=forms.ChoiceField(GetSubstationEquipmentModelTypeChoices(substationEquipment.SubstationEquipmentModelType), required=False)
    Dict['InventoryNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'40'}))
    Dict['CatalogNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'40'}))
    Dict['RatedTransmissionVoltage1']=forms.ChoiceField(GetTransmissionVoltageChoices(substationEquipment.RatedTransmissionVoltage1), required=False)
    Dict['RatedTransmissionVoltage2']=forms.ChoiceField(GetTransmissionVoltageChoices(substationEquipment.RatedTransmissionVoltage2), required=False)
    Dict['RatedDistributionVoltage1']=forms.ChoiceField(GetDistributionVoltageChoices(substationEquipment.RatedDistributionVoltage1), required=False)
    Dict['RatedDistributionVoltage2']=forms.ChoiceField(GetDistributionVoltageChoices(substationEquipment.RatedDistributionVoltage2), required=False)
    Dict['OperatorControlVoltage']=forms.ChoiceField(GetServiceVoltageChoices(substationEquipment.OperatorControlVoltage), required=False)
    Dict['CurrentTransmissionVoltage']=forms.ChoiceField(GetTransmissionVoltageChoices(substationEquipment.CurrentTransmissionVoltage), required=False)
    Dict['CurrentDistributionVoltage']=forms.ChoiceField(GetDistributionVoltageChoices(substationEquipment.CurrentDistributionVoltage), required=False)
    Dict['KVARating']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['MVARating']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['Manufacturer']=forms.ChoiceField(GetManufacturerChoices(substationEquipment.Manufacturer), required=False)
    Dict['DateOfManufacture']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['Impedance']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['OilCapacityGallon']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['WeightPound']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['BatteryChargerManufacturer']=forms.ChoiceField(GetManufacturerChoices(substationEquipment.BatteryChargerManufacturer), required=False)
    Dict['BatteryChargerDateOfManufacture']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['BatteryChargerInputVoltage']=forms.ChoiceField(GetServiceVoltageChoices(substationEquipment.BatteryChargerInputVoltage), required=False)
    Dict['BatteryChargerOutputVoltage']=forms.ChoiceField(GetServiceVoltageChoices(substationEquipment.BatteryChargerOutputVoltage), required=False)
    Dict['BatteryChargerACAmps']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['BatteryChargerDCAmps']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['BatteryChargerNumberOfCells']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['BatteryChargerTypeOfCells']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['BatteryBankBatteryVoltage']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['BatteryBankBatteryAmpHours']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['BatteryBankBatteryReserveCapacity']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['BatteryBankBatteryModelNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['SubstationEquipmentOverCurrentRelayType']=forms.ChoiceField(GetSubstationEquipmentModelTypeChoices(substationEquipment.SubstationEquipmentOverCurrentRelayType), required=False)
    Dict['SubstationEquipmentDifferentialRelayType']=forms.ChoiceField(GetSubstationEquipmentModelTypeChoices(substationEquipment.SubstationEquipmentDifferentialRelayType), required=False)
    Dict['SubstationEquipmentRegulatorControllerType']=forms.ChoiceField(GetSubstationEquipmentModelTypeChoices(substationEquipment.SubstationEquipmentRegulatorControllerType), required=False)
    Dict['RegulatorControllerSerialNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserControllerType']=forms.ChoiceField(GetSubstationEquipmentModelTypeChoices(substationEquipment.RecloserControllerType), required=False)
    Dict['SerialNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['Description']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'40'}))
    Dict['ActiveIndicator']=forms.BooleanField(required=False)
    Dict['Assemblyid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['SubstationEquipmentTemplate']=forms.ChoiceField(GetSubstationEquipmentTemplateChoices(substationEquipment.SubstationEquipmentTemplate), required=False)
    Dict['SubstationEquipmentid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5', 'READONLY':'True'}))    
    Dict['SubstationEquipmentSetting']=forms.ChoiceField(GetSubstationEquipmentSettingChoices(substationEquipment.GetSubstationEquipmentSettingAssignment()), required=False)
    Dict['SubstationCircuit']=forms.ChoiceField(GetSubstationCircuitChoices(substationEquipment.GetSubstationCircuitAssignment()), required=False)
    #Action Fields
    Dict['UpdateIndicator']=forms.BooleanField(required=False)
    Dict['NewIndicator']=forms.BooleanField(required=False)    
    return Dict


def ProcessSubstationEquipmentForm(form, UserName):
    import models
    UpdateIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateIndicator')
    NewIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NewIndicator')
    SubstationEquipmentName=COOPGIS_FormMisc.FormGetString(form, 'SubstationEquipmentName')
    InventoryNumber=COOPGIS_FormMisc.FormGetString(form, 'InventoryNumber')
    CatalogNumber=COOPGIS_FormMisc.FormGetString(form, 'CatalogNumber')
    RatedTransmissionVoltage1=COOPGIS_FormMisc.FormGetObjectFromid(form, 'RatedTransmissionVoltage1', Voltage)
    if(RatedTransmissionVoltage1):
        RatedTransmissionVoltage1id, RatedTransmissionVoltage1IndexWhenReverseSorted=RatedTransmissionVoltage1.GetCommandidData()
    else:
        RatedTransmissionVoltage1id=RatedTransmissionVoltage1IndexWhenReverseSorted=-1 
    RatedTransmissionVoltage2=COOPGIS_FormMisc.FormGetObjectFromid(form, 'RatedTransmissionVoltage2', Voltage)
    if(RatedTransmissionVoltage2):
        RatedTransmissionVoltage2id, RatedTransmissionVoltage2IndexWhenReverseSorted=RatedTransmissionVoltage2.GetCommandidData()
    else:
        RatedTransmissionVoltage2id=RatedTransmissionVoltage2IndexWhenReverseSorted=-1 
    RatedDistributionVoltage1=COOPGIS_FormMisc.FormGetObjectFromid(form, 'RatedDistributionVoltage1', Voltage)
    if(RatedDistributionVoltage1):
        RatedDistributionVoltage1id, RatedDistributionVoltage1IndexWhenReverseSorted=RatedDistributionVoltage1.GetCommandidData()
    else:
        RatedDistributionVoltage1id=RatedDistributionVoltage1IndexWhenReverseSorted=-1 
    RatedDistributionVoltage2=COOPGIS_FormMisc.FormGetObjectFromid(form, 'RatedDistributionVoltage2', Voltage)
    if(RatedDistributionVoltage2):
        RatedDistributionVoltage2id, RatedDistributionVoltage2IndexWhenReverseSorted=RatedDistributionVoltage2.GetCommandidData()
    else:
        RatedDistributionVoltage2id=RatedDistributionVoltage2IndexWhenReverseSorted=-1 
    OperatorControlVoltage=COOPGIS_FormMisc.FormGetObjectFromid(form, 'OperatorControlVoltage', Voltage)
    if(OperatorControlVoltage):
        OperatorControlVoltageid, OperatorControlVoltageIndexWhenReverseSorted=OperatorControlVoltage.GetCommandidData()
    else:
        OperatorControlVoltageid=OperatorControlVoltageIndexWhenReverseSorted=-1 
    CurrentTransmissionVoltage=COOPGIS_FormMisc.FormGetObjectFromid(form, 'CurrentTransmissionVoltage', Voltage)
    if(CurrentTransmissionVoltage):
        CurrentTransmissionVoltageid, CurrentTransmissionVoltageIndexWhenReverseSorted=CurrentTransmissionVoltage.GetCommandidData()
    else:
        CurrentTransmissionVoltageid=CurrentTransmissionVoltageIndexWhenReverseSorted=-1 
    CurrentDistributionVoltage=COOPGIS_FormMisc.FormGetObjectFromid(form, 'CurrentDistributionVoltage', Voltage)
    if(CurrentDistributionVoltage):
        CurrentDistributionVoltageid, CurrentDistributionVoltageIndexWhenReverseSorted=CurrentDistributionVoltage.GetCommandidData()
    else:
        CurrentDistributionVoltageid=CurrentDistributionVoltageIndexWhenReverseSorted=-1 
    KVARating=COOPGIS_FormMisc.FormGetFloat(form, 'KVARating')
    MVARating=COOPGIS_FormMisc.FormGetFloat(form, 'MVARating')
    Manufacturer=COOPGIS_FormMisc.FormGetObjectFromid(form, 'Manufacturer', Company)
    if(Manufacturer):
        Manufacturerid, ManufacturerIndexWhenReverseSorted=Manufacturer.GetCommandidData()
    else:
        Manufacturerid=ManufacturerIndexWhenReverseSorted=-1 
    DateOfManufacture=COOPGIS_FormMisc.FormGetDateTime(form, 'DateOfManufacture')
    Impedance=COOPGIS_FormMisc.FormGetFloat(form, 'Impedance')
    OilCapacityGallon=COOPGIS_FormMisc.FormGetFloat(form, 'OilCapacityGallon')
    WeightPound=COOPGIS_FormMisc.FormGetFloat(form, 'WeightPound')
    BatteryChargerManufacturer=COOPGIS_FormMisc.FormGetObjectFromid(form, 'BatteryChargerManufacturer', Company)
    if(BatteryChargerManufacturer):
        BatteryChargerManufacturerid, BatteryChargerManufacturerIndexWhenReverseSorted=BatteryChargerManufacturer.GetCommandidData()
    else:
        BatteryChargerManufacturerid=BatteryChargerManufacturerIndexWhenReverseSorted=-1 
    BatteryChargerDateOfManufacture=COOPGIS_FormMisc.FormGetDateTime(form, 'BatteryChargerDateOfManufacture')
    BatteryChargerInputVoltage=COOPGIS_FormMisc.FormGetObjectFromid(form, 'BatteryChargerInputVoltage', Voltage)
    if(BatteryChargerInputVoltage):
        BatteryChargerInputVoltageid, BatteryChargerInputVoltageIndexWhenReverseSorted=BatteryChargerInputVoltage.GetCommandidData()
    else:
        BatteryChargerInputVoltageid=BatteryChargerInputVoltageIndexWhenReverseSorted=-1 
    BatteryChargerOutputVoltage=COOPGIS_FormMisc.FormGetObjectFromid(form, 'BatteryChargerOutputVoltage', Voltage)
    if(BatteryChargerOutputVoltage):
        BatteryChargerOutputVoltageid, BatteryChargerOutputVoltageIndexWhenReverseSorted=BatteryChargerOutputVoltage.GetCommandidData()
    else:
        BatteryChargerOutputVoltageid=BatteryChargerOutputVoltageIndexWhenReverseSorted=-1 
    BatteryChargerACAmps=COOPGIS_FormMisc.FormGetFloat(form, 'BatteryChargerACAmps')
    BatteryChargerDCAmps=COOPGIS_FormMisc.FormGetFloat(form, 'BatteryChargerDCAmps')
    BatteryChargerNumberOfCells=COOPGIS_FormMisc.FormGetInteger(form, 'BatteryChargerNumberOfCells')
    BatteryChargerTypeOfCells=COOPGIS_FormMisc.FormGetString(form, 'BatteryChargerTypeOfCells')
    BatteryBankBatteryVoltage=COOPGIS_FormMisc.FormGetFloat(form, 'BatteryBankBatteryVoltage')
    BatteryBankBatteryAmpHours=COOPGIS_FormMisc.FormGetFloat(form, 'BatteryBankBatteryAmpHours')
    BatteryBankBatteryReserveCapacity=COOPGIS_FormMisc.FormGetFloat(form, 'BatteryBankBatteryAmpHours')
    BatteryBankBatteryModelNumber=COOPGIS_FormMisc.FormGetString(form, 'BatteryBankBatteryModelNumber')
    SubstationEquipmentOverCurrentRelayType=COOPGIS_FormMisc.FormGetObjectFromid(form, 'SubstationEquipmentOverCurrentRelayType', SubstationEquipmentModelType)
    if(SubstationEquipmentOverCurrentRelayType):
        SubstationEquipmentOverCurrentRelayTypeid, SubstationEquipmentOverCurrentRelayTypeIndexWhenReverseSorted=SubstationEquipmentOverCurrentRelayType.GetCommandidData()
    else:
        SubstationEquipmentOverCurrentRelayTypeid=SubstationEquipmentOverCurrentRelayTypeIndexWhenReverseSorted=-1 
    SubstationEquipmentDifferentialRelayType=COOPGIS_FormMisc.FormGetObjectFromid(form, 'SubstationEquipmentDifferentialRelayType', SubstationEquipmentModelType)
    if(SubstationEquipmentDifferentialRelayType):
        SubstationEquipmentDifferentialRelayTypeid, SubstationEquipmentDifferentialRelayTypeIndexWhenReverseSorted=SubstationEquipmentDifferentialRelayType.GetCommandidData()
    else:
        SubstationEquipmentDifferentialRelayTypeid=SubstationEquipmentDifferentialRelayTypeIndexWhenReverseSorted=-1 
    SubstationEquipmentRegulatorControllerType=COOPGIS_FormMisc.FormGetObjectFromid(form, 'SubstationEquipmentRegulatorControllerType', SubstationEquipmentModelType)
    if(SubstationEquipmentRegulatorControllerType):
        SubstationEquipmentRegulatorControllerTypeid, SubstationEquipmentRegulatorControllerTypeIndexWhenReverseSorted=SubstationEquipmentRegulatorControllerType.GetCommandidData()
    else:
        SubstationEquipmentRegulatorControllerTypeid=SubstationEquipmentRegulatorControllerTypeIndexWhenReverseSorted=-1 
    RegulatorControllerSerialNumber=COOPGIS_FormMisc.FormGetString(form, 'RegulatorControllerSerialNumber')
    RecloserControllerType=COOPGIS_FormMisc.FormGetObjectFromid(form, 'RecloserControllerType', SubstationEquipmentModelType)
    if(RecloserControllerType):
        RecloserControllerTypeid, RecloserControllerTypeIndexWhenReverseSorted=RecloserControllerType.GetCommandidData()
    else:
        RecloserControllerTypeid=RecloserControllerTypeIndexWhenReverseSorted=-1 
    SerialNumber=COOPGIS_FormMisc.FormGetString(form, 'SerialNumber')
    Description=COOPGIS_FormMisc.FormGetString(form, 'Description')
    ActiveIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ActiveIndicator')
    substationEquipmentTemplate=COOPGIS_FormMisc.FormGetObjectFromid(form, 'SubstationEquipmentTemplate', SubstationEquipmentTemplate)
    if(substationEquipmentTemplate):
        SubstationEquipmentTemplateid, SubstationEquipmentTemplateIndexWhenReverseSorted=substationEquipmentTemplate.GetCommandidData()
    else:
        SubstationEquipmentTemplateid=SubstationEquipmentTemplateIndexWhenReverseSorted=-1 
    SubstationEquipmentid=COOPGIS_FormMisc.FormGetInteger(form, 'SubstationEquipmentid')
    Assemblyid=COOPGIS_FormMisc.FormGetString(form, 'Assemblyid')
    try:     
        assembly=Assembly.objects.filter(id=Assemblyid)[0]
        Assemblyid, AssemblyIndexWhenReverseSorted=assembly.GetCommandidData()
    except:
        assembly=None
        Assemblyid=AssemblyIndexWhenReverseSorted=-1
    if(not assembly):
        Assemblyid=None
    SubstationEquipmentSelectionid=COOPGIS_FormMisc.FormGetInteger(form, 'SubstationEquipmentSelection')
    try:
        substationEquipment=SubstationEquipment.objects.filter(id=SubstationEquipmentSelectionid)[0]
    except:
        substationEquipment=None
    substationEquipmentModelType=COOPGIS_FormMisc.FormGetObjectFromid(form, 'SubstationEquipmentModelType', SubstationEquipmentModelType)
    if(substationEquipmentModelType):
        SubstationEquipmentModelTypeid, SubstationEquipmentModelTypeIndexWhenReverseSorted=substationEquipmentModelType.GetCommandidData()
    else:
        SubstationEquipmentModelTypeid, SubstationEquipmentModelTypeIndexWhenReverseSorted = (-1,-1)
    
    command=Command()
    if(NewIndicator):
        command=command.Create(Name='CreateSubstationEquipment', SubstationEquipmentName=SubstationEquipmentName, InventoryNumber=InventoryNumber, CatalogNumber=CatalogNumber, 
                               RatedTransmissionVoltage1id=RatedTransmissionVoltage1id, 
                               RatedTransmissionVoltage1IndexWhenReverseSorted=RatedTransmissionVoltage1IndexWhenReverseSorted, 
                               RatedTransmissionVoltage2id=RatedTransmissionVoltage2id, 
                               RatedTransmissionVoltage2IndexWhenReverseSorted=RatedTransmissionVoltage2IndexWhenReverseSorted,
                               RatedDistributionVoltage1id=RatedDistributionVoltage1id, 
                               RatedDistributionVoltage1IndexWhenReverseSorted=RatedDistributionVoltage1IndexWhenReverseSorted, 
                               RatedDistributionVoltage2id=RatedDistributionVoltage2id, 
                               RatedDistributionVoltage2IndexWhenReverseSorted=RatedDistributionVoltage2IndexWhenReverseSorted,
                               OperatorControlVoltageid=OperatorControlVoltageid, 
                               OperatorControlVoltageIndexWhenReverseSorted=OperatorControlVoltageIndexWhenReverseSorted,
                               CurrentTransmissionVoltageid=CurrentTransmissionVoltageid, 
                               CurrentTransmissionVoltageIndexWhenReverseSorted=CurrentTransmissionVoltageIndexWhenReverseSorted,
                               CurrentDistributionVoltageid=CurrentDistributionVoltageid, 
                               CurrentDistributionVoltageIndexWhenReverseSorted=CurrentDistributionVoltageIndexWhenReverseSorted,
                               KVARating=KVARating, MVARating=MVARating,
                               Manufacturerid=Manufacturerid, ManufacturerIndexWhenReverseSorted=ManufacturerIndexWhenReverseSorted,
                               DateOfManufacture=DateOfManufacture, Impedance=Impedance, OilCapacityGallon=OilCapacityGallon, 
                               WeightPound=WeightPound,
                               BatteryChargerManufacturerid=BatteryChargerManufacturerid, 
                               BatteryChargerManufacturerIndexWhenReverseSorted=BatteryChargerManufacturerIndexWhenReverseSorted,
                               BatteryChargerDateOfManufacture=BatteryChargerDateOfManufacture, 
                               BatteryChargerInputVoltageid=BatteryChargerInputVoltageid, 
                               BatteryChargerInputVoltageIndexWhenReverseSorted=BatteryChargerInputVoltageIndexWhenReverseSorted,
                               BatteryChargerOutputVoltageid=BatteryChargerOutputVoltageid, 
                               BatteryChargerOutputVoltageIndexWhenReverseSorted=BatteryChargerOutputVoltageIndexWhenReverseSorted,
                               BatteryChargerACAmps=BatteryChargerACAmps, BatteryChargerDCAmps=BatteryChargerDCAmps, 
                               BatteryChargerNumberOfCells=BatteryChargerNumberOfCells,
                               BatteryChargerTypeOfCells=BatteryChargerTypeOfCells, BatteryBankBatteryVoltage=BatteryBankBatteryVoltage, 
                               BatteryBankBatteryAmpHours=BatteryBankBatteryAmpHours,
                               BatteryBankBatteryReserveCapacity=BatteryBankBatteryReserveCapacity, BatteryBankBatteryModelNumber=BatteryBankBatteryModelNumber, 
                               SubstationEquipmentOverCurrentRelayTypeid=SubstationEquipmentOverCurrentRelayTypeid, 
                               SubstationEquipmentOverCurrentRelayTypeIndexWhenReverseSorted=SubstationEquipmentOverCurrentRelayTypeIndexWhenReverseSorted, 
                               SubstationEquipmentDifferentialRelayTypeid=SubstationEquipmentDifferentialRelayTypeid, 
                               SubstationEquipmentDifferentialRelayTypeIndexWhenReverseSorted=SubstationEquipmentDifferentialRelayTypeIndexWhenReverseSorted,
                               SubstationEquipmentRegulatorControllerTypeid=SubstationEquipmentRegulatorControllerTypeid, 
                               SubstationEquipmentRegulatorControllerTypeIndexWhenReverseSorted=SubstationEquipmentRegulatorControllerTypeIndexWhenReverseSorted,
                               RegulatorControllerSerialNumber=RegulatorControllerSerialNumber,
                               RecloserControllerTypeid=RecloserControllerTypeid, 
                               RecloserControllerTypeIndexWhenReverseSorted=RecloserControllerTypeIndexWhenReverseSorted, 
                               SerialNumber=SerialNumber, Description=Description, Assemblyid=Assemblyid, 
                               AssemblyIndexWhenReverseSorted=AssemblyIndexWhenReverseSorted, 
                               ActiveIndicator=ActiveIndicator,
                               SubstationEquipmentTemplateid=SubstationEquipmentTemplateid, 
                               SubstationEquipmentTemplateIndexWhenReverseSorted=SubstationEquipmentTemplateIndexWhenReverseSorted,
                               SubstationEquipmentModelTypeid=SubstationEquipmentModelTypeid, 
                               SubstationEquipmentModelTypeIndexWhenReverseSorted=SubstationEquipmentModelTypeIndexWhenReverseSorted,
                               CommandUserName=UserName)
        substationEquipment=command.Process()
        substation=COOPGIS_FormMisc.FormGetObjectFromid(form, 'Substation', Substation)
        if(substation and substationEquipment):
            Substationid, SubstationIndexWhenReverseSorted=substation.GetCommandidData()
            SubstationEquipmentid, SubstationEquipmentIndexWhenReverseSorted=substationEquipment.GetCommandidData()
            SubstationAssignmentCommand=Command().Create(Name='CreateSubstationEquipmentSubstationAssignment', Substationid=Substationid,
                                                       SubstationIndexWhenReverseSorted=SubstationIndexWhenReverseSorted,
                                                       SubstationEquipmentid=SubstationEquipmentid, 
                                                       SubstationEquipmentIndexWhenReverseSorted=SubstationEquipmentIndexWhenReverseSorted,
                                                       Description='', DateTime=datetime.datetime.now(), CommandUserName=UserName)
            SubstationAssignmentCommand.Process()
        substationEquipmentSetting=COOPGIS_FormMisc.FormGetObjectFromid(form, 'SubstationEquipmentSetting', SubstationEquipmentSetting)
        if(substationEquipment and substationEquipmentSetting):
            SubstationEquipmentSettingid, SubstationEquipmentSettingIndexWhenReverseSorted=substationEquipmentSetting.GetCommandidData()
            SubstationEquipmentid, SubstationEquipmentIndexWhenReverseSorted=substationEquipment.GetCommandidData()
            SubstationEquipmentSettingAssignmentCommand=Command().Create(Name='CreateSubstationEquipmentSettingAssignment', 
                                                       SubstationEquipmentSettingid=SubstationEquipmentSettingid, 
                                                       SubstationEquipmentSettingIndexWhenReverseSorted=SubstationEquipmentSettingIndexWhenReverseSorted,
                                                       SubstationEquipmentid=SubstationEquipmentid, 
                                                       SubstationEquipmentIndexWhenReverseSorted=SubstationEquipmentIndexWhenReverseSorted,
                                                       DateTime=datetime.datetime.now(), CommandUserName=UserName)
            SubstationEquipmentSettingAssignmentCommand.Process()
        substationCircuit=COOPGIS_FormMisc.FormGetObjectFromid(form, 'SubstationCircuit', SubstationCircuit)
        if(substationEquipment and substationCircuit):
            SubstationCircuitid, SubstationCircuitIndexWhenReverseSorted=substationCircuit.GetCommandidData()
            SubstationEquipmentid, SubstationEquipmentIndexWhenReverseSorted=substationEquipment.GetCommandidData()
            SubstationCircuitAssignmentCommand=Command().Create(Name='CreateSubstationEquipmentCircuitAssignment', 
                                                       SubstationCircuitid=SubstationCircuitid, 
                                                       SubstationCircuitIndexWhenReverseSorted=SubstationCircuitIndexWhenReverseSorted,
                                                       SubstationEquipmentid=SubstationEquipmentid, Description='', 
                                                       SubstationEquipmentIndexWhenReverseSorted=SubstationEquipmentIndexWhenReverseSorted,
                                                       DateTime=datetime.datetime.now(), CommandUserName=UserName)
            SubstationCircuitAssignmentCommand.Process()
    elif(UpdateIndicator and COOPGIS_FormMisc.FormGetInteger(form, 'SubstationEquipmentid')):
        SubstationEquipmentid=COOPGIS_FormMisc.FormGetInteger(form, 'SubstationEquipmentid')
        substationEquipment=SubstationEquipment.objects.filter(id=SubstationEquipmentid)[0]
        Objectid, ObjectIndexWhenReverseSorted=substationEquipment.GetCommandidData()
        command=command.Create(Name='EditSubstationEquipment', Objectid=Objectid, ObjectIndexWhenReverseSorted=ObjectIndexWhenReverseSorted,
                               SubstationEquipmentName=SubstationEquipmentName, InventoryNumber=InventoryNumber, CatalogNumber=CatalogNumber, 
                               RatedTransmissionVoltage1id=RatedTransmissionVoltage1id, 
                               RatedTransmissionVoltage1IndexWhenReverseSorted=RatedTransmissionVoltage1IndexWhenReverseSorted, 
                               RatedTransmissionVoltage2id=RatedTransmissionVoltage2id, 
                               RatedTransmissionVoltage2IndexWhenReverseSorted=RatedTransmissionVoltage2IndexWhenReverseSorted,
                               RatedDistributionVoltage1id=RatedDistributionVoltage1id, 
                               RatedDistributionVoltage1IndexWhenReverseSorted=RatedDistributionVoltage1IndexWhenReverseSorted, 
                               RatedDistributionVoltage2id=RatedDistributionVoltage2id, 
                               RatedDistributionVoltage2IndexWhenReverseSorted=RatedDistributionVoltage2IndexWhenReverseSorted,
                               OperatorControlVoltageid=OperatorControlVoltageid, 
                               OperatorControlVoltageIndexWhenReverseSorted=OperatorControlVoltageIndexWhenReverseSorted,
                               CurrentTransmissionVoltageid=CurrentTransmissionVoltageid, 
                               CurrentTransmissionVoltageIndexWhenReverseSorted=CurrentTransmissionVoltageIndexWhenReverseSorted,
                               CurrentDistributionVoltageid=CurrentDistributionVoltageid, 
                               CurrentDistributionVoltageIndexWhenReverseSorted=CurrentDistributionVoltageIndexWhenReverseSorted,
                               KVARating=KVARating, MVARating=MVARating,
                               Manufacturerid=Manufacturerid, ManufacturerIndexWhenReverseSorted=ManufacturerIndexWhenReverseSorted,
                               DateOfManufacture=DateOfManufacture, Impedance=Impedance, OilCapacityGallon=OilCapacityGallon, 
                               WeightPound=WeightPound,
                               BatteryChargerManufacturerid=BatteryChargerManufacturerid, 
                               BatteryChargerManufacturerIndexWhenReverseSorted=BatteryChargerManufacturerIndexWhenReverseSorted,
                               BatteryChargerDateOfManufacture=BatteryChargerDateOfManufacture, 
                               BatteryChargerInputVoltageid=BatteryChargerInputVoltageid, 
                               BatteryChargerInputVoltageIndexWhenReverseSorted=BatteryChargerInputVoltageIndexWhenReverseSorted,
                               BatteryChargerOutputVoltageid=BatteryChargerOutputVoltageid, 
                               BatteryChargerOutputVoltageIndexWhenReverseSorted=BatteryChargerOutputVoltageIndexWhenReverseSorted,
                               BatteryChargerACAmps=BatteryChargerACAmps, BatteryChargerDCAmps=BatteryChargerDCAmps, 
                               BatteryChargerNumberOfCells=BatteryChargerNumberOfCells,
                               BatteryChargerTypeOfCells=BatteryChargerTypeOfCells, BatteryBankBatteryVoltage=BatteryBankBatteryVoltage, 
                               BatteryBankBatteryAmpHours=BatteryBankBatteryAmpHours,
                               BatteryBankBatteryReserveCapacity=BatteryBankBatteryReserveCapacity, BatteryBankBatteryModelNumber=BatteryBankBatteryModelNumber, 
                               SubstationEquipmentOverCurrentRelayTypeid=SubstationEquipmentOverCurrentRelayTypeid, 
                               SubstationEquipmentOverCurrentRelayTypeIndexWhenReverseSorted=SubstationEquipmentOverCurrentRelayTypeIndexWhenReverseSorted, 
                               SubstationEquipmentDifferentialRelayTypeid=SubstationEquipmentDifferentialRelayTypeid, 
                               SubstationEquipmentDifferentialRelayTypeIndexWhenReverseSorted=SubstationEquipmentDifferentialRelayTypeIndexWhenReverseSorted,
                               SubstationEquipmentRegulatorControllerTypeid=SubstationEquipmentRegulatorControllerTypeid, 
                               SubstationEquipmentRegulatorControllerTypeIndexWhenReverseSorted=SubstationEquipmentRegulatorControllerTypeIndexWhenReverseSorted,
                               RegulatorControllerSerialNumber=RegulatorControllerSerialNumber,
                               RecloserControllerTypeid=RecloserControllerTypeid, 
                               RecloserControllerTypeIndexWhenReverseSorted=RecloserControllerTypeIndexWhenReverseSorted, 
                               SerialNumber=SerialNumber, Description=Description, Assemblyid=Assemblyid, 
                               AssemblyIndexWhenReverseSorted=AssemblyIndexWhenReverseSorted, 
                               ActiveIndicator=ActiveIndicator,
                               SubstationEquipmentTemplateid=SubstationEquipmentTemplateid, 
                               SubstationEquipmentTemplateIndexWhenReverseSorted=SubstationEquipmentTemplateIndexWhenReverseSorted,
                               SubstationEquipmentModelTypeid=SubstationEquipmentModelTypeid, 
                               SubstationEquipmentModelTypeIndexWhenReverseSorted=SubstationEquipmentModelTypeIndexWhenReverseSorted,
                               CommandUserName=UserName)
        substationEquipment=command.Process()

        substation=COOPGIS_FormMisc.FormGetObjectFromid(form, 'Substation', Substation)
        if(substationEquipment):
            PreviousSubstation=substationEquipment.GetSubstation()
        if(substation and substationEquipment and PreviousSubstation != substation):
            Substationid, SubstationIndexWhenReverseSorted=substation.GetCommandidData()
            SubstationEquipmentid, SubstationEquipmentIndexWhenReverseSorted=substationEquipment.GetCommandidData()
            SubstationAssignmentCommand=Command().Create(Name='CreateSubstationEquipmentSubstationAssignment', Substationid=Substationid,
                                                         SubstationIndexWhenReverseSorted=SubstationIndexWhenReverseSorted,
                                                         SubstationEquipmentid=SubstationEquipmentid, 
                                                         SubstationEquipmentIndexWhenReverseSorted=SubstationEquipmentIndexWhenReverseSorted,
                                                         Description='', DateTime=datetime.datetime.now(), CommandUserName=UserName)
            SubstationAssignmentCommand.Process()
        substationEquipmentSetting=COOPGIS_FormMisc.FormGetObjectFromid(form, 'SubstationEquipmentSetting', SubstationEquipmentSetting)
        if(substationEquipment and substationEquipmentSetting):
            SubstationEquipmentSettingid, SubstationEquipmentSettingIndexWhenReverseSorted=substationEquipmentSetting.GetCommandidData()
            SubstationEquipmentid, SubstationEquipmentIndexWhenReverseSorted=substationEquipment.GetCommandidData()
            SubstationEquipmentSettingAssignmentCommand=Command().Create(Name='CreateSubstationEquipmentSettingAssignment', 
                                                       SubstationEquipmentSettingid=SubstationEquipmentSettingid, 
                                                       SubstationEquipmentSettingIndexWhenReverseSorted=SubstationEquipmentSettingIndexWhenReverseSorted,
                                                       SubstationEquipmentid=SubstationEquipmentid, 
                                                       SubstationEquipmentIndexWhenReverseSorted=SubstationEquipmentIndexWhenReverseSorted,
                                                       DateTime=datetime.datetime.now(), CommandUserName=UserName)
            SubstationEquipmentSettingAssignmentCommand.Process()
        substationCircuit=COOPGIS_FormMisc.FormGetObjectFromid(form, 'SubstationCircuit', SubstationCircuit)
        if(substationEquipment and substationCircuit):
            SubstationCircuitid, SubstationCircuitIndexWhenReverseSorted=substationCircuit.GetCommandidData()
            SubstationEquipmentid, SubstationEquipmentIndexWhenReverseSorted=substationEquipment.GetCommandidData()
            SubstationCircuitAssignmentCommand=Command().Create(Name='CreateSubstationEquipmentCircuitAssignment', 
                                                       SubstationCircuitid=SubstationCircuitid, 
                                                       SubstationCircuitIndexWhenReverseSorted=SubstationCircuitIndexWhenReverseSorted,
                                                       SubstationEquipmentid=SubstationEquipmentid, Description='', 
                                                       SubstationEquipmentIndexWhenReverseSorted=SubstationEquipmentIndexWhenReverseSorted,
                                                       DateTime=datetime.datetime.now(), CommandUserName=UserName)
            SubstationCircuitAssignmentCommand.Process()

    return substationEquipment

def PopulateSubstationEquipmentForm(form, substationEquipment):
    form.data['UpdateIndicator']=False
    form.data['NewIndicator']=False
    if(substationEquipment):
        form.data['SubstationEquipmentName']=substationEquipment.Name
        form.data['InventoryNumber']=substationEquipment.InventoryNumber
        form.data['CatalogNumber']=substationEquipment.CatalogNumber
        if(substationEquipment.RatedTransmissionVoltage1):
            form.setData({'RatedTransmissionVoltage1': substationEquipment.RatedTransmissionVoltage1.id})
        else:
            form.setData({'RatedTransmissionVoltage1': -1})
        if(substationEquipment.RatedTransmissionVoltage2):
            form.setData({'RatedTransmissionVoltage2': substationEquipment.RatedTransmissionVoltage2.id})
        else:
            form.setData({'RatedTransmissionVoltage2': -1})
        if(substationEquipment.RatedDistributionVoltage1):
            form.setData({'RatedDistributionVoltage1': substationEquipment.RatedDistributionVoltage1.id})
        else:
            form.setData({'RatedDistributionVoltage1': -1})
        if(substationEquipment.RatedDistributionVoltage2):
            form.setData({'RatedDistributionVoltage2': substationEquipment.RatedDistributionVoltage2.id})
        else:
            form.setData({'RatedDistributionVoltage2': -1})
        if(substationEquipment.OperatorControlVoltage):
            form.setData({'OperatorControlVoltage': substationEquipment.OperatorControlVoltage.id})
        else:
            form.setData({'OperatorControlVoltage': -1})
        if(substationEquipment.CurrentTransmissionVoltage):
            form.setData({'CurrentTransmissionVoltage': substationEquipment.CurrentTransmissionVoltage.id})
        else:
            form.setData({'CurrentTransmissionVoltage': -1})
        if(substationEquipment.CurrentDistributionVoltage):
            form.setData({'CurrentDistributionVoltage': substationEquipment.CurrentDistributionVoltage.id})
        else:
            form.setData({'CurrentDistributionVoltage': -1})
        form.data['KVARating']=substationEquipment.KVARating
        form.data['MVARating']=substationEquipment.MVARating
        if(substationEquipment.Manufacturer):
            form.setData({'Manufacturer': substationEquipment.Manufacturer.id})
        else:
            form.setData({'Manufacturer': -1})
        form.data['DateOfManufacture']=substationEquipment.DateOfManufacture
        form.data['Impedance']=substationEquipment.Impedance
        form.data['OilCapacityGallon']=substationEquipment.OilCapacityGallon
        form.data['WeightPound']=substationEquipment.WeightPound
        if(substationEquipment.BatteryChargerManufacturer):
            form.setData({'BatteryChargerManufacturer': substationEquipment.BatteryChargerManufacturer.id})
        else:
            form.setData({'BatteryChargerManufacturer': -1})
        form.data['BatteryChargerDateOfManufacture']=substationEquipment.BatteryChargerDateOfManufacture

        if(substationEquipment.BatteryChargerInputVoltage):
            form.setData({'BatteryChargerInputVoltage': substationEquipment.BatteryChargerInputVoltage.id})
        else:
            form.setData({'BatteryChargerInputVoltage': -1})
        if(substationEquipment.BatteryChargerOutputVoltage):
            form.setData({'BatteryChargerOutputVoltage': substationEquipment.BatteryChargerOutputVoltage.id})
        else:
            form.setData({'BatteryChargerOutputVoltage': -1})
        form.data['BatteryChargerACAmps']=substationEquipment.BatteryChargerACAmps
        form.data['BatteryChargerDCAmps']=substationEquipment.BatteryChargerDCAmps
        form.data['BatteryChargerNumberOfCells']=substationEquipment.BatteryChargerNumberOfCells
        form.data['BatteryChargerTypeOfCells']=substationEquipment.BatteryChargerTypeOfCells
        form.data['BatteryBankBatteryVoltage']=substationEquipment.BatteryBankBatteryVoltage
        form.data['BatteryBankBatteryAmpHours']=substationEquipment.BatteryBankBatteryAmpHours
        form.data['BatteryBankBatteryReserveCapacity']=substationEquipment.BatteryBankBatteryReserveCapacity
        form.data['BatteryBankBatteryModelNumber']=substationEquipment.BatteryBankBatteryModelNumber 
        if(substationEquipment.SubstationEquipmentOverCurrentRelayType):
            form.setData({'SubstationEquipmentOverCurrentRelayType': substationEquipment.SubstationEquipmentOverCurrentRelayType.id})
        else:
            form.setData({'SubstationEquipmentOverCurrentRelayType': -1})
        if(substationEquipment.SubstationEquipmentDifferentialRelayType):
            form.setData({'SubstationEquipmentDifferentialRelayType': substationEquipment.SubstationEquipmentDifferentialRelayType.id})
        else:
            form.setData({'SubstationEquipmentDifferentialRelayType': -1})
        if(substationEquipment.SubstationEquipmentRegulatorControllerType):
            form.setData({'SubstationEquipmentRegulatorControllerType': substationEquipment.SubstationEquipmentRegulatorControllerType.id})
        else:
            form.setData({'SubstationEquipmentRegulatorControllerType': -1})
        form.data['RegulatorControllerSerialNumber']=substationEquipment.RegulatorControllerSerialNumber
        if(substationEquipment.RecloserControllerType):
            form.setData({'RecloserControllerType': substationEquipment.RecloserControllerType.id})
        else:
            form.setData({'RecloserControllerType': -1})
        form.data['SerialNumber']=substationEquipment.SerialNumber
        form.data['Description']=substationEquipment.Description
        form.data['ActiveIndicator']=substationEquipment.ActiveIndicator
        if(substationEquipment.SubstationEquipmentTemplate):
            form.setData({'SubstationEquipmentTemplate': substationEquipment.SubstationEquipmentTemplate.id})
        else:
            form.setData({'SubstationEquipmentTemplate': -1})
        form.data['SubstationEquipmentid']=substationEquipment.id
        if(substationEquipment.Assembly):
            form.data['Assemblyid']=substationEquipment.Assembly.id
        else:
            form.data['Assemblyid']=''
        substation=substationEquipment.GetSubstation()
        if(substation):
            form.data['Substation']=substation.id
        else:
            form.data['Substation']='-1' 
        if(substationEquipment.GetSubstationEquipmentSettingAssignment()):
            form.setData({'SubstationEquipmentSetting': substationEquipment.GetSubstationEquipmentSettingAssignment().id})
        else:
            form.setData({'SubstationEquipmentSetting': -1})
        if(substationEquipment.GetSubstationCircuitAssignment()):
            form.setData({'SubstationCircuit': substationEquipment.GetSubstationCircuitAssignment().id})
        else:
            form.setData({'SubstationCircuit': -1})
    else:
        form.data['SubstationEquipmentName']=''
        form.data['InventoryNumber']=''
        form.data['CatalogNumber']=''
        form.setData({'RatedTransmissionVoltage1': -1})
        form.setData({'RatedTransmissionVoltage2': -1})
        form.setData({'RatedDistributionVoltage1': -1})
        form.setData({'RatedDistributionVoltage2': -1})
        form.setData({'OperatorControlVoltage': -1})
        form.setData({'CurrentTransmissionVoltage': -1})
        form.setData({'CurrentDistributionVoltage': -1})
        form.data['KVARating']=''
        form.data['MVARating']=''
        form.setData({'Manufacturer': -1})
        form.data['DateOfManufacture']=''
        form.data['Impedance']=''
        form.data['OilCapacityGallon']=''
        form.data['WeightPound']=''
        form.setData({'BatteryChargerManufacturer': -1})
        form.data['BatteryChargerDateOfManufacture']=''
        form.setData({'BatteryChargerInputVoltage': -1})
        form.setData({'BatteryChargerOutputVoltage': -1})
        form.data['BatteryChargerACAmps']=''
        form.data['BatteryChargerDCAmps']=''
        form.data['BatteryChargerNumberOfCells']=''
        form.data['BatteryChargerTypeOfCells']=''
        form.data['BatteryBankBatteryVoltage']=''
        form.data['BatteryBankBatteryAmpHours']=''
        form.data['BatteryBankBatteryReserveCapacity']=''
        form.data['BatteryBankBatteryModelNumber']='' 
        form.setData({'SubstationEquipmentOverCurrentRelayType': -1})
        form.setData({'SubstationEquipmentDifferentialRelayType': -1})
        form.setData({'SubstationEquipmentRegulatorControllerType': -1})
        form.data['RegulatorControllerSerialNumber']=''
        form.setData({'RecloserControllerType': -1})
        form.data['SerialNumber']=''
        form.data['Description']=''
        form.data['ActiveIndicator']=''
        form.setData({'SubstationEquipmentTemplate': -1})
        form.data['SubstationEquipmentid']=''
        form.data['Assemblyid']=''
        form.data['Substation']='-1'
    return form

def GetSubstationEquipmentChoices(default=None):
    SubstationEquipmentChoices=[]
    if(default):
        SubstationEquipmentChoices.append([default.id, str(default)])
    SubstationEquipmentChoices.append((-1, 'None Selected'))
    SubstationEquipments=SubstationEquipment.objects.all().order_by('id')
    for i in SubstationEquipments:
        if(not [i.id, str(i)] in SubstationEquipmentChoices):
            SubstationEquipmentChoices.append([i.id, str(i)])
    return SubstationEquipmentChoices

def BuildSubstationEquipmentTestForm(substationEquipmentTest):
    from django.contrib import admin
    Dict={}
    SubstationEquipmentTestChoices=[]
    if(substationEquipmentTest):
        SubstationEquipmentTestChoices.append([substationEquipmentTest.id, str(substationEquipmentTest.SubstationEquipment)])
    SubstationEquipmentTestChoices.append((-1, 'None Selected'))
    SubstationEquipmentTests=SubstationEquipmentTest.objects.all().order_by('id')
    for i in SubstationEquipmentTests:
        if(not [i.id, str(i.SubstationEquipment.InventoryNumber)] in SubstationEquipmentTestChoices):
            SubstationEquipmentTestChoices.append([i.id, str(i.SubstationEquipment)])
    Dict['SubstationEquipmentTestSelection']=forms.ChoiceField(SubstationEquipmentTestChoices, required=False)
    if(not substationEquipmentTest):
        substationEquipmentTest=SubstationEquipmentTest()
        SubstationEquipmentChoice=None
    else:
        SubstationEquipmentChoice=substationEquipmentTest.SubstationEquipment
    Dict['SubstationEquipmentTestid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5', 'READONLY':'True'}))    
    Dict['SubstationEquipmentid']=forms.ChoiceField(GetSubstationEquipmentChoices(SubstationEquipmentChoice), required=False)
    Dict['Description']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['PassIndicator']=forms.BooleanField(required=False)
    Dict['DateTime']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    #Action Fields
    Dict['UpdateIndicator']=forms.BooleanField(required=False)
    Dict['NewIndicator']=forms.BooleanField(required=False)
    return Dict

def ProcessSubstationEquipmentTestForm(form, UserName):
    import models
    UpdateIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateIndicator')
    NewIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NewIndicator')
    Description=COOPGIS_FormMisc.FormGetString(form, 'Description')
    PassIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'PassIndicator')
    DateTime=COOPGIS_FormMisc.FormGetDateTime(form, 'DateTime')
    SubstationEquipmentid=COOPGIS_FormMisc.FormGetInteger(form, 'SubstationEquipmentid')
    SubstationEquipmentTestid=COOPGIS_FormMisc.FormGetInteger(form, 'SubstationEquipmentTestSelection')
    try:
        substationEquipmentTest=SubstationEquipmentTest.objects.filter(id=SubstationEquipmentTestid)[0]
    except:
        substationEquipmentTest=None
    try:
        substationEquipment=SubstationEquipment.objects.filter(id=SubstationEquipmentid)[0]
        substationEquipmentid, SubstationEquipmentIndexWhenReverseSorted=substationEquipment.GetCommandidData()
    except:
        substationEquipment=None
        substationEquipmentid=SubstationEquipmentIndexWhenReverseSorted=-1
    command=Command()    
    if(NewIndicator):
        DateTime=str(datetime.datetime.now())
        command=command.Create(Name='CreateSubstationEquipmentTest', Description=Description, SubstationEquipmentid=SubstationEquipmentid, 
                               SubstationEquipmentIndexWhenReverseSorted=SubstationEquipmentIndexWhenReverseSorted, PassIndicator=PassIndicator,
                               DateTime=DateTime, CommandUserName=UserName)
        substation=command.Process()
    elif(UpdateIndicator and COOPGIS_FormMisc.FormGetInteger(form, 'SubstationEquipmentTestid')):
        DateTime=str(datetime.datetime.now())
        SubstationEquipmentTestid=COOPGIS_FormMisc.FormGetInteger(form, 'SubstationEquipmentTestid')
        substationEquipmentTest=SubstationEquipmentTest.objects.filter(id=SubstationEquipmentTestid)[0]
        Objectid, ObjectIndexWhenReverseSorted=substationEquipmentTest.GetCommandidData()
        command=command.Create(Name='EditSubstationEquipmentTest', Objectid=Objectid, 
                               Description=Description, SubstationEquipmentid=SubstationEquipmentid, ObjectIndexWhenReverseSorted=ObjectIndexWhenReverseSorted,
                               SubstationEquipmentIndexWhenReverseSorted=SubstationEquipmentIndexWhenReverseSorted, PassIndicator=PassIndicator,
                               DateTime=DateTime, CommandUserName=UserName)
        substationEquipmentTest=command.Process()
    return substationEquipmentTest

def PopulateSubstationEquipmentTestForm(form, substationEquipmentTest):
    form.data['UpdateIndicator']=False
    form.data['NewIndicator']=False
    if(substationEquipmentTest):
        form.data['SubstationEquipmentid']=substationEquipmentTest.SubstationEquipment.id
        form.data['SubstationEquipmentTestid']=substationEquipmentTest.id
        form.data['Description']=substationEquipmentTest.Description
        form.data['PassIndicator']=substationEquipmentTest.PassIndicator
        form.data['DateTime']=substationEquipmentTest.DateTime
    else:
        form.data['SubstationEquipmentid']=''
        form.data['SubstationEquipmentTestid']=''
        form.data['Description']=''
        form.data['PassIndicator']=''
        form.data['DateTime']=''
    return form

def GetInspectionChoices(default=None):
    InspectionChoices=[]
    if(default):
        InspectionChoices.append([default.id, str(default)])
    InspectionChoices.append((-1, 'None Selected'))
    Inspections=SubstationInspectionChoice.objects.all().order_by('Name')
    for i in Inspections:
        if(not [i.id, str(i)] in InspectionChoices):
            InspectionChoices.append([i.id, str(i)])
    return InspectionChoices

def BuildSubstationInspectionForm(substationInspection):
    from django.contrib import admin
    Dict={}
    SubstationInspectionChoices=[]
    if(substationInspection):
        SubstationInspectionChoices.append([substationInspection.id, str(substationInspection)])
    SubstationInspectionChoices.append((-1, 'None Selected'))
    SubstationInspections=SubstationInspection.objects.all().order_by('id')
    for i in SubstationInspections:
        if(not [i.id, str(i)] in SubstationInspectionChoices):
            SubstationInspectionChoices.append([i.id, str(i)])
    Dict['SubstationInspectionSelection']=forms.ChoiceField(SubstationInspectionChoices, required=False)
    if(not substationInspection):
        substationInspection=SubstationInspection()
        substation=None
        DynasphereVisual=None
        BrokenPorcelain=None
        CircuitIdentifier=None
        SurgeProtectorVisual=None
        Debris=None
        FenceGroundLevel=None
        FenceOverallCondition=None
        FenceSecurityWire=None
        FenceWarningSign=None
        GateGround=None
        GateLock=None
        GateWarningSign=None
        MaterialStore=None
        SpillPreventionPlan=None
        AMRVisual=None
        Vegetation=None
    else:
        substation=substationInspection.Substation
        DynasphereVisual=substationInspection.DynasphereVisual
        BrokenPorcelain=substationInspection.BrokenPorcelain
        CircuitIdentifier=substationInspection.CircuitIdentifier
        SurgeProtectorVisual=substationInspection.SurgeProtectorVisual
        Debris=substationInspection.Debris
        FenceGroundLevel=substationInspection.FenceGroundLevel
        FenceOverallCondition=substationInspection.FenceOverallCondition
        FenceSecurityWire=substationInspection.FenceSecurityWire
        FenceWarningSign=substationInspection.FenceWarningSign
        GateGround=substationInspection.GateGround
        GateLock=substationInspection.GateLock
        GateWarningSign=substationInspection.GateWarningSign
        MaterialStore=substationInspection.MaterialStore
        SpillPreventionPlan=substationInspection.SpillPreventionPlan
        AMRVisual=substationInspection.AMRVisual
        Vegetation=substationInspection.Vegetation
    Dict['SubstationInspectionid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5', 'READONLY':'True'})) 
    Dict['Description']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['CreateDateTime']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'22', 'READONLY':'True'}))
    Dict['CreateUserName']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'22', 'READONLY':'True'}))
    Dict['LastModifyDateTime']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'22', 'READONLY':'True'}))
    Dict['LastModifyUserName']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'22', 'READONLY':'True'}))
    Dict['DynasphereVisual']=forms.ChoiceField(GetInspectionChoices(DynasphereVisual), required=False)
    Dict['BrokenPorcelain']=forms.ChoiceField(GetInspectionChoices(BrokenPorcelain), required=False)
    Dict['CircuitIdentifier']=forms.ChoiceField(GetInspectionChoices(CircuitIdentifier), required=False)
    Dict['DynasphereOperationIndicator']=forms.BooleanField(required=False)
    Dict['SurgeProtectorVisual']=forms.ChoiceField(GetInspectionChoices(SurgeProtectorVisual), required=False)    
    Dict['Debris']=forms.ChoiceField(GetInspectionChoices(Debris), required=False)
    Dict['FenceGroundLevel']=forms.ChoiceField(GetInspectionChoices(FenceGroundLevel), required=False)
    Dict['FenceOverallCondition']=forms.ChoiceField(GetInspectionChoices(FenceOverallCondition), required=False)
    Dict['FenceSecurityWire']=forms.ChoiceField(GetInspectionChoices(FenceSecurityWire), required=False)
    Dict['FenceWarningSign']=forms.ChoiceField(GetInspectionChoices(FenceWarningSign), required=False)
    Dict['GateGround']=forms.ChoiceField(GetInspectionChoices(GateGround), required=False)
    Dict['GateLock']=forms.ChoiceField(GetInspectionChoices(GateLock), required=False)
    Dict['GateWarningSign']=forms.ChoiceField(GetInspectionChoices(GateWarningSign), required=False)
    Dict['MaterialStore']=forms.ChoiceField(GetInspectionChoices(MaterialStore), required=False)
    Dict['SpillPreventionPlan']=forms.ChoiceField(GetInspectionChoices(SpillPreventionPlan), required=False)
    Dict['AMRVisual']=forms.ChoiceField(GetInspectionChoices(AMRVisual), required=False)
    Dict['Vegetation']=forms.ChoiceField(GetInspectionChoices(Vegetation), required=False)
    #Action Fields
    Dict['UpdateIndicator']=forms.BooleanField(required=False)
    Dict['NewIndicator']=forms.BooleanField(required=False)
    return Dict

def ProcessSubstationInspectionForm(form, UserName, substation):
    import models
    UpdateIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateIndicator')
    NewIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NewIndicator')
    substationInspectionSelection=COOPGIS_FormMisc.FormGetObjectFromid(form, 'SubstationInspectionSelection', SubstationInspection)
    substationInspection=substationInspectionSelection
    if(substationInspectionSelection):
        SubstationInspectionSelectionid, SubstationInspectionSelectionIndexWhenReverseSorted=substationInspectionSelection.GetCommandidData()
    else:
        SubstationInspectionSelectionid=SubstationInspectionSelectionIndexWhenReverseSorted=-1
    Substationid, SubstationIndexWhenReverseSorted=substation.GetCommandidData()
    Description=COOPGIS_FormMisc.FormGetString(form, 'Description')
    DynasphereVisual=COOPGIS_FormMisc.FormGetObjectFromid(form, 'DynasphereVisual', SubstationInspectionChoice)
    if(DynasphereVisual):
        DynasphereVisualid, DynasphereVisualIndexWhenReverseSorted=DynasphereVisual.GetCommandidData()
    else:
        DynasphereVisualid, DynasphereVisualIndexWhenReverseSorted = (-1,-1)
    BrokenPorcelain=COOPGIS_FormMisc.FormGetObjectFromid(form, 'BrokenPorcelain', SubstationInspectionChoice)
    if(BrokenPorcelain):
        BrokenPorcelainid, BrokenPorcelainIndexWhenReverseSorted=BrokenPorcelain.GetCommandidData()
    else:
        BrokenPorcelainid, BrokenPorcelainIndexWhenReverseSorted = (-1,-1)
    CircuitIdentifier=COOPGIS_FormMisc.FormGetObjectFromid(form, 'CircuitIdentifier', SubstationInspectionChoice)
    if(CircuitIdentifier):
        CircuitIdentifierid, CircuitIdentifierIndexWhenReverseSorted=CircuitIdentifier.GetCommandidData()
    else:
        CircuitIdentifierid, CircuitIdentifierIndexWhenReverseSorted= (-1,-1)   
    DynasphereOperationIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'DynasphereOperationIndicator')
    SurgeProtectorVisual=COOPGIS_FormMisc.FormGetObjectFromid(form, 'SurgeProtectorVisual', SubstationInspectionChoice)
    if(SurgeProtectorVisual):
        SurgeProtectorVisualid, SurgeProtectorVisualIndexWhenReverseSorted=SurgeProtectorVisual.GetCommandidData()
    else:
        SurgeProtectorVisualid, SurgeProtectorVisualIndexWhenReverseSorted=(-1,-1)
    Debris=COOPGIS_FormMisc.FormGetObjectFromid(form, 'Debris', SubstationInspectionChoice)
    if(Debris):
        Debrisid, DebrisIndexWhenReverseSorted=Debris.GetCommandidData()
    else:
        Debrisid, DebrisIndexWhenReverseSorted=(-1,-1)
    FenceGroundLevel=COOPGIS_FormMisc.FormGetObjectFromid(form, 'FenceGroundLevel', SubstationInspectionChoice)
    if(FenceGroundLevel):
        FenceGroundLevelid, FenceGroundLevelIndexWhenReverseSorted=FenceGroundLevel.GetCommandidData()
    else:
        FenceGroundLevelid, FenceGroundLevelIndexWhenReverseSorted=(-1,-1)
    FenceOverallCondition=COOPGIS_FormMisc.FormGetObjectFromid(form, 'FenceOverallCondition', SubstationInspectionChoice)
    if(FenceOverallCondition):
        FenceOverallConditionid, FenceOverallConditionIndexWhenReverseSorted=FenceOverallCondition.GetCommandidData()
    else:
        FenceOverallConditionid, FenceOverallConditionIndexWhenReverseSorted=(-1,-1)
    FenceSecurityWire=COOPGIS_FormMisc.FormGetObjectFromid(form, 'FenceSecurityWire', SubstationInspectionChoice)
    if(FenceSecurityWire):
        FenceSecurityWireid, FenceSecurityWireIndexWhenReverseSorted=FenceSecurityWire.GetCommandidData()
    else:
        FenceSecurityWireid, FenceSecurityWireIndexWhenReverseSorted=(-1,-1)
    FenceWarningSign=COOPGIS_FormMisc.FormGetObjectFromid(form, 'FenceWarningSign', SubstationInspectionChoice)
    if(FenceWarningSign):
        FenceWarningSignid, FenceWarningSignIndexWhenReverseSorted=FenceWarningSign.GetCommandidData()
    else:
        FenceWarningSignid, FenceWarningSignIndexWhenReverseSorted=(-1,-1)
    GateGround=COOPGIS_FormMisc.FormGetObjectFromid(form, 'GateGround', SubstationInspectionChoice)
    if(GateGround):
        GateGroundid, GateGroundIndexWhenReverseSorted=GateGround.GetCommandidData()
    else:
        GateGroundid, GateGroundIndexWhenReverseSorted=(-1,-1)
    GateLock=COOPGIS_FormMisc.FormGetObjectFromid(form, 'GateLock', SubstationInspectionChoice)
    if(GateLock):
        GateLockid, GateLockIndexWhenReverseSorted=GateLock.GetCommandidData()
    else:
        GateLockid, GateLockIndexWhenReverseSorted=(-1,-1)
    GateWarningSign=COOPGIS_FormMisc.FormGetObjectFromid(form, 'GateWarningSign', SubstationInspectionChoice)
    if(GateWarningSign):
        GateWarningSignid, GateWarningSignIndexWhenReverseSorted=GateWarningSign.GetCommandidData()
    else:
        GateWarningSignid, GateWarningSignIndexWhenReverseSorted=(-1,-1)
    MaterialStore=COOPGIS_FormMisc.FormGetObjectFromid(form, 'MaterialStore', SubstationInspectionChoice)
    if(MaterialStore):
        MaterialStoreid, MaterialStoreIndexWhenReverseSorted=MaterialStore.GetCommandidData()
    else:
        MaterialStoreid, MaterialStoreIndexWhenReverseSorted=(-1,-1)
    SpillPreventionPlan=COOPGIS_FormMisc.FormGetObjectFromid(form, 'SpillPreventionPlan', SubstationInspectionChoice)
    if(SpillPreventionPlan):
        SpillPreventionPlanid, SpillPreventionPlanIndexWhenReverseSorted=SpillPreventionPlan.GetCommandidData()
    else:
        SpillPreventionPlanid, SpillPreventionPlanIndexWhenReverseSorted=(-1,-1)        
    AMRVisual=COOPGIS_FormMisc.FormGetObjectFromid(form, 'AMRVisual', SubstationInspectionChoice)
    if(AMRVisual):
        AMRVisualid, AMRVisualIndexWhenReverseSorted=AMRVisual.GetCommandidData()
    else:
        AMRVisualid, AMRVisualIndexWhenReverseSorted=(-1,-1)
    Vegetation=COOPGIS_FormMisc.FormGetObjectFromid(form, 'Vegetation', SubstationInspectionChoice)
    if(Vegetation):
        Vegetationid, VegetationIndexWhenReverseSorted=Vegetation.GetCommandidData()
    else:
        Vegetationid, VegetationIndexWhenReverseSorted=(-1,-1)
    command=Command()    
    DateTime=str(datetime.datetime.now())
    if(NewIndicator):
        command=command.Create(Name='CreateSubstationInspection', Substationid=Substationid, SubstationIndexWhenReverseSorted=SubstationIndexWhenReverseSorted,
                               Description=Description, CreateDateTime=DateTime, CreateUserName=UserName, 
                               DynasphereVisualid=DynasphereVisualid, DynasphereVisualIndexWhenReverseSorted=DynasphereVisualIndexWhenReverseSorted, 
                               BrokenPorcelainid=BrokenPorcelainid, BrokenPorcelainIndexWhenReverseSorted=BrokenPorcelainIndexWhenReverseSorted,
                               CircuitIdentifierid=CircuitIdentifierid, CircuitIdentifierIndexWhenReverseSorted=CircuitIdentifierIndexWhenReverseSorted, 
                               DynasphereOperationIndicator=DynasphereOperationIndicator,
                               SurgeProtectorVisualid=SurgeProtectorVisualid, SurgeProtectorVisualIndexWhenReverseSorted=SurgeProtectorVisualIndexWhenReverseSorted, 
                               Debrisid=Debrisid, DebrisIndexWhenReverseSorted=DebrisIndexWhenReverseSorted, 
                               FenceGroundLevelid=FenceGroundLevelid, FenceGroundLevelIndexWhenReverseSorted=FenceGroundLevelIndexWhenReverseSorted, 
                               FenceOverallConditionid=FenceOverallConditionid, FenceOverallConditionIndexWhenReverseSorted=FenceOverallConditionIndexWhenReverseSorted, 
                               FenceSecurityWireid=FenceSecurityWireid, FenceSecurityWireIndexWhenReverseSorted=FenceSecurityWireIndexWhenReverseSorted,
                               FenceWarningSignid=FenceWarningSignid, FenceWarningSignIndexWhenReverseSorted=FenceWarningSignIndexWhenReverseSorted,
                               GateGroundid=GateGroundid, GateGroundIndexWhenReverseSorted=GateGroundIndexWhenReverseSorted,
                               GateLockid=GateLockid, GateLockIndexWhenReverseSorted=GateLockIndexWhenReverseSorted, 
                               GateWarningSignid=GateWarningSignid, GateWarningSignIndexWhenReverseSorted=GateWarningSignIndexWhenReverseSorted, 
                               MaterialStoreid=MaterialStoreid, MaterialStoreIndexWhenReverseSorted=MaterialStoreIndexWhenReverseSorted,
                               SpillPreventionPlanid=SpillPreventionPlanid, SpillPreventionPlanIndexWhenReverseSorted=SpillPreventionPlanIndexWhenReverseSorted, 
                               AMRVisualid=AMRVisualid, AMRVisualIndexWhenReverseSorted=AMRVisualIndexWhenReverseSorted,
                               Vegetationid=Vegetationid, VegetationIndexWhenReverseSorted=VegetationIndexWhenReverseSorted,
                               DateTime=DateTime, CommandUserName=UserName)
        substationInspection=command.Process()
    elif(UpdateIndicator and COOPGIS_FormMisc.FormGetInteger(form, 'SubstationInspectionid')):
        DateTime=str(DateTime)
        SubstationInspectionid=COOPGIS_FormMisc.FormGetInteger(form, 'SubstationInspectionid')
        substationInspection=SubstationInspection.objects.filter(id=SubstationInspectionid)[0]
        Objectid, ObjectIndexWhenReverseSorted=substationInspection.GetCommandidData()
        command=command.Create(Name='EditSubstationInspection', Objectid=Objectid, ObjectIndexWhenReverseSorted=ObjectIndexWhenReverseSorted,
                               Substationid=Substationid, SubstationIndexWhenReverseSorted=SubstationIndexWhenReverseSorted,
                               Description=Description, LastModifyDateTime=DateTime, LastModifyUserName=UserName,
                               DynasphereVisualid=DynasphereVisualid, DynasphereVisualIndexWhenReverseSorted=DynasphereVisualIndexWhenReverseSorted, 
                               BrokenPorcelainid=BrokenPorcelainid, BrokenPorcelainIndexWhenReverseSorted=BrokenPorcelainIndexWhenReverseSorted,
                               CircuitIdentifierid=CircuitIdentifierid, CircuitIdentifierIndexWhenReverseSorted=CircuitIdentifierIndexWhenReverseSorted, 
                               DynasphereOperationIndicator=DynasphereOperationIndicator,
                               SurgeProtectorVisualid=SurgeProtectorVisualid, SurgeProtectorVisualIndexWhenReverseSorted=SurgeProtectorVisualIndexWhenReverseSorted, 
                               Debrisid=Debrisid, DebrisIndexWhenReverseSorted=DebrisIndexWhenReverseSorted, 
                               FenceGroundLevelid=FenceGroundLevelid, FenceGroundLevelIndexWhenReverseSorted=FenceGroundLevelIndexWhenReverseSorted, 
                               FenceOverallConditionid=FenceOverallConditionid, FenceOverallConditionIndexWhenReverseSorted=FenceOverallConditionIndexWhenReverseSorted, 
                               FenceSecurityWireid=FenceSecurityWireid, FenceSecurityWireIndexWhenReverseSorted=FenceSecurityWireIndexWhenReverseSorted,
                               FenceWarningSignid=FenceWarningSignid, FenceWarningSignIndexWhenReverseSorted=FenceWarningSignIndexWhenReverseSorted,
                               GateGroundid=GateGroundid, GateGroundIndexWhenReverseSorted=GateGroundIndexWhenReverseSorted,
                               GateLockid=GateLockid, GateLockIndexWhenReverseSorted=GateLockIndexWhenReverseSorted, 
                               GateWarningSignid=GateWarningSignid, GateWarningSignIndexWhenReverseSorted=GateWarningSignIndexWhenReverseSorted, 
                               MaterialStoreid=MaterialStoreid, MaterialStoreIndexWhenReverseSorted=MaterialStoreIndexWhenReverseSorted,
                               SpillPreventionPlanid=SpillPreventionPlanid, SpillPreventionPlanIndexWhenReverseSorted=SpillPreventionPlanIndexWhenReverseSorted, 
                               AMRVisualid=AMRVisualid, AMRVisualIndexWhenReverseSorted=AMRVisualIndexWhenReverseSorted,
                               Vegetationid=Vegetationid, VegetationIndexWhenReverseSorted=VegetationIndexWhenReverseSorted,
                               DateTime=DateTime, CommandUserName=UserName)
        substationInspection=command.Process()
    return substationInspection

def PopulateSubstationInspectionForm(form, substationInspection):
    form.data['UpdateIndicator']=False
    form.data['NewIndicator']=False
    if(substationInspection):
        form.data['SubstationInspectionSelection']=substationInspection.id
        form.data['SubstationInspectionid']=substationInspection.id
        form.data['Description']=substationInspection.Description
        form.data['CreateDateTime']=substationInspection.CreateDateTime
        form.data['CreateUserName']=substationInspection.CreateUserName    
        form.data['LastModifyDateTime']=substationInspection.LastModifyDateTime
        form.data['LastModifyUserName']=substationInspection.LastModifyUserName
        if(substationInspection.DynasphereVisual):
            form.setData({'DynasphereVisual': substationInspection.DynasphereVisual.id})
        else:
            form.setData({'DynasphereVisual': -1})
        if(substationInspection.BrokenPorcelain):
            form.setData({'BrokenPorcelain': substationInspection.BrokenPorcelain.id})
        else:
            form.setData({'BrokenPorcelain': -1})
        if(substationInspection.CircuitIdentifier):
            form.setData({'CircuitIdentifier': substationInspection.CircuitIdentifier.id})
        else:
            form.setData({'CircuitIdentifier': -1})
        form.data['DynasphereOperationIndicator']=substationInspection.DynasphereOperationIndicator
        if(substationInspection.SurgeProtectorVisual):
            form.setData({'SurgeProtectorVisual': substationInspection.SurgeProtectorVisual.id})
        else:
            form.setData({'SurgeProtectorVisual': -1})
        if(substationInspection.Debris):
            form.setData({'Debris': substationInspection.Debris.id})
        else:
            form.setData({'Debris': -1})
        if(substationInspection.FenceGroundLevel):
            form.setData({'FenceGroundLevel': substationInspection.FenceGroundLevel.id})
        else:
            form.setData({'FenceGroundLevel': -1})
        if(substationInspection.FenceOverallCondition):
            form.setData({'FenceOverallCondition': substationInspection.FenceOverallCondition.id})
        else:
            form.setData({'FenceOverallCondition': -1})
        if(substationInspection.FenceSecurityWire):
            form.setData({'FenceSecurityWire': substationInspection.FenceSecurityWire.id})
        else:
            form.setData({'FenceSecurityWire': -1})
        if(substationInspection.FenceWarningSign):
            form.setData({'FenceWarningSign': substationInspection.FenceWarningSign.id})
        else:
            form.setData({'FenceWarningSign': -1})
        if(substationInspection.GateGround):
            form.setData({'GateGround': substationInspection.GateGround.id})
        else:
            form.setData({'GateGround': -1})
        if(substationInspection.GateLock):
            form.setData({'GateLock': substationInspection.GateLock.id})
        else:
            form.setData({'GateLock': -1})
        if(substationInspection.GateWarningSign):
            form.setData({'GateWarningSign': substationInspection.GateWarningSign.id})
        else:
            form.setData({'GateWarningSign': -1})
        if(substationInspection.MaterialStore):
            form.setData({'MaterialStore': substationInspection.MaterialStore.id})
        else:
            form.setData({'MaterialStore': -1})
        if(substationInspection.SpillPreventionPlan):
            form.setData({'SpillPreventionPlan': substationInspection.SpillPreventionPlan.id})
        else:
            form.setData({'SpillPreventionPlan': -1})
        if(substationInspection.AMRVisual):
            form.setData({'AMRVisual': substationInspection.AMRVisual.id})
        else:
            form.setData({'AMRVisual': -1})
        if(substationInspection.Vegetation):
            form.setData({'Vegetation': substationInspection.Vegetation.id})
        else:
            form.setData({'Vegetation': -1})
    else:
        form.setData({'SubstationInspectionSelection': -1})
        form.data['SubstationInspectionid']=''
        form.data['Description']=''
        form.data['CreateDateTime']=''
        form.data['CreateUserName']=''
        form.data['LastModifyDateTime']=''
        form.data['LastModifyUserName']=''
        form.setData({'SurgeProtectorVisual': -1})
        form.setData({'BrokenPorcelain': -1})
        form.setData({'CircuitIdentifier': -1})
        form.setData({'DynasphereVisual': -1})
        form.setData({'DynasphereOperationIndicator': False})
        form.setData({'SurgeProtectorVisual': -1})
        form.setData({'Debris': -1})
        form.setData({'FenceGroundLevel': -1})
        form.setData({'FenceOverallCondition': -1})
        form.setData({'FenceSecurityWire': -1})
        form.setData({'FenceWarningSign': -1})
        form.setData({'GateGround': -1})
        form.setData({'GateLock': -1})
        form.setData({'GateWarningSign': -1})
        form.setData({'MaterialStore': -1})
        form.setData({'SpillPreventionPlan': -1})
        form.setData({'AMRVisual': -1})
        form.setData({'Vegetation': -1})
    return form

def BuildSubstationEquipmentInspectionForm(SpecialBuildInfo):
    substationEquipmentInspection=SpecialBuildInfo[0]
    substation=SpecialBuildInfo[1]
    from django.contrib import admin
    Dict={}
    SubstationEquipmentInspectionChoices=[]
    if(substationEquipmentInspection):
        SubstationEquipmentInspectionChoices.append([substationEquipmentInspection.id, str(substationEquipmentInspection)])
    SubstationEquipmentInspectionChoices.append((-1, 'None Selected'))
    SubstationEquipmentInspections=SubstationEquipmentInspection.objects.filter(SubstationEquipment__CurrentSubstation=substation).order_by('id')
    for i in SubstationEquipmentInspections:
        if(not [i.id, str(i)] in SubstationEquipmentInspectionChoices):
            SubstationEquipmentInspectionChoices.append([i.id, str(i)])
    Dict['SubstationEquipmentInspectionSelection']=forms.ChoiceField(SubstationEquipmentInspectionChoices, required=False)
    if(not substationEquipmentInspection):
        substationEquipmentInspection=SubstationEquipmentInspection()
        BatteryTest=None
        BatteryVisual=None
        Ground=None
        Visual=None
        MeterVisual=None
        SurgeProtectorVisual=None
        TransformerOilLeak=None
        TransformerOilLevel=None
        TransformerNitrogenPressure=None
        TransformerOilVisual=None
        MechanismCharge=None
        FanWorkingVisual=None
    else:
        BatteryTest=substationEquipmentInspection.BatteryTest
        BatteryVisual=substationEquipmentInspection.BatteryVisual
        Ground=substationEquipmentInspection.Ground
        Visual=substationEquipmentInspection.Visual
        MeterVisual=substationEquipmentInspection.MeterVisual
        SurgeProtectorVisual=substationEquipmentInspection.SurgeProtectorVisual
        TransformerOilLeak=substationEquipmentInspection.TransformerOilLeak
        TransformerOilLevel=substationEquipmentInspection.TransformerOilLevel
        TransformerNitrogenPressure=substationEquipmentInspection.TransformerNitrogenPressure
        TransformerOilVisual=substationEquipmentInspection.TransformerOilVisual
        MechanismCharge=substationEquipmentInspection.MechanismCharge
        FanWorkingVisual=substationEquipmentInspection.FanWorkingVisual
    Dict['SubstationEquipmentInspectionid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5', 'READONLY':'True'})) 
    Dict['Description']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'30'}))
    Dict['CreateDateTime']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5', 'READONLY':'True'}))
    Dict['CreateUserName']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5', 'READONLY':'True'}))
    Dict['LastModifyDateTime']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5', 'READONLY':'True'}))
    Dict['LastModifyUserName']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5', 'READONLY':'True'}))
    Dict['BatteryTest']=forms.ChoiceField(GetInspectionChoices(BatteryTest), required=False)
    Dict['BatteryCharge']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['BatteryVisual']=forms.ChoiceField(GetInspectionChoices(BatteryVisual), required=False)
    Dict['BatteryVoltageTest']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['BatteryVoltageNormal']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['Ground']=forms.ChoiceField(GetInspectionChoices(Ground), required=False)
    Dict['Visual']=forms.ChoiceField(GetInspectionChoices(Visual), required=False)
    Dict['MeterKWH']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['MeterKW']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['MeterVisual']=forms.ChoiceField(GetInspectionChoices(MeterVisual), required=False)
    Dict['RecloserAmperageA']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserAmperageB']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserAmperageC']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserAmperageGround']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserMaxDemandA']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserMaxDemandB']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserMaxDemandC']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserMaxDemandGround']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserOperationSummaryA']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserOperationSummaryB']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserOperationSummaryC']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserTargetA']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserTargetB']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserTargetC']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RecloserTargetGround']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RegulatorDragHandPositionMinimum']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RegulatorDragHandPositionCurrent']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RegulatorDragHandPositionMaximum']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RegulatorVoltHigh']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RegulatorVoltLow']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RegulatorVoltCurrent']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['RegulatorMaxAmp']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['SurgeProtectorVisual']=forms.ChoiceField(GetInspectionChoices(SurgeProtectorVisual), required=False)
    Dict['TransformerOilLeak']=forms.ChoiceField(GetInspectionChoices(TransformerOilLeak), required=False)
    Dict['TransformerOilLevel']=forms.ChoiceField(GetInspectionChoices(TransformerOilLevel), required=False)
    Dict['TransformerOilTemperatureCurrent']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['TransformerOilTemperatureMaximum']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['TransformerNitrogenPressure']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['TransformerWindingTemperatureCurrent']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['TransformerWindingTemperatureMaximum']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['TransformerOilVisual']=forms.ChoiceField(GetInspectionChoices(TransformerOilVisual), required=False)
    Dict['MechanismCharge']=forms.ChoiceField(GetInspectionChoices(MechanismCharge), required=False)
    Dict['OperationCounter']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['FanWorkingVisual']=forms.ChoiceField(GetInspectionChoices(FanWorkingVisual), required=False)
    Dict['DemandAmpA']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['DemandAmpB']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['DemandAmpC']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['OverCurrentTrip']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['BreakerCounter']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))

    #Action Fields

    Dict['UpdateIndicator']=forms.BooleanField(required=False)
    Dict['NewIndicator']=forms.BooleanField(required=False)
    return Dict

def ProcessSubstationEquipmentInspectionForm(form, UserName, substation, substationEquipment):
    import models
    UpdateIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateIndicator')
    NewIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NewIndicator')
    substationEquipmentInspectionSelection=COOPGIS_FormMisc.FormGetObjectFromid(form, 'SubstationEquipmentInspectionSelection', SubstationEquipmentInspection)
    substationEquipmentInspection=substationEquipmentInspectionSelection
    if(substationEquipmentInspectionSelection):
        SubstationEquipmentInspectionSelectionid, SubstationEquipmentInspectionSelectionIndexWhenReverseSorted=substationEquipmentInspectionSelection.GetCommandidData()
    else:
        SubstationEquipmentInspectionSelectionid=SubstationEquipmentInspectionSelectionIndexWhenReverseSorted=-1
    Substationid, SubstationIndexWhenReverseSorted=substation.GetCommandidData()
    SubstationEquipmentid, SubstationEquipmentIndexWhenReverseSorted=substationEquipment.GetCommandidData()
    Description=COOPGIS_FormMisc.FormGetString(form, 'Description')
    BatteryTest=COOPGIS_FormMisc.FormGetObjectFromid(form, 'BatteryTest', SubstationInspectionChoice)
    if(BatteryTest):
        BatteryTestid, BatteryTestIndexWhenReverseSorted=BatteryTest.GetCommandidData()
    else:
        BatteryTestid, BatteryTestIndexWhenReverseSorted = (-1,-1)
    BatteryCharge=COOPGIS_FormMisc.FormGetFloat(form, 'BatteryCharge')
    BatteryVisual=COOPGIS_FormMisc.FormGetObjectFromid(form, 'BatteryVisual', SubstationInspectionChoice)
    if(BatteryVisual):
        BatteryVisualid, BatteryVisualIndexWhenReverseSorted=BatteryVisual.GetCommandidData()
    else:
        BatteryVisualid, BatteryVisualIndexWhenReverseSorted = (-1,-1)
    BatteryVoltageTest=COOPGIS_FormMisc.FormGetFloat(form, 'BatteryVoltageTest')
    BatteryVoltageNormal=COOPGIS_FormMisc.FormGetFloat(form, 'BatteryVoltageNormal')
    Ground=COOPGIS_FormMisc.FormGetObjectFromid(form, 'Ground', SubstationInspectionChoice)
    if(Ground):
        Groundid, GroundIndexWhenReverseSorted=Ground.GetCommandidData()
    else:
        Groundid, GroundIndexWhenReverseSorted = (-1,-1)
    Visual=COOPGIS_FormMisc.FormGetObjectFromid(form, 'Visual', SubstationInspectionChoice)
    if(Visual):
        Visualid, VisualIndexWhenReverseSorted=Visual.GetCommandidData()
    else:
        Visualid, VisualIndexWhenReverseSorted = (-1,-1)
    MeterKWH=COOPGIS_FormMisc.FormGetFloat(form, 'MeterKWH')
    MeterKW=COOPGIS_FormMisc.FormGetFloat(form, 'MeterKW')
    MeterVisual=COOPGIS_FormMisc.FormGetObjectFromid(form, 'MeterVisual', SubstationInspectionChoice)
    if(MeterVisual):
        MeterVisualid, MeterVisualIndexWhenReverseSorted=MeterVisual.GetCommandidData()
    else:
        MeterVisualid, MeterVisualIndexWhenReverseSorted = (-1,-1)
    RecloserAmperageA=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserAmperageA')
    RecloserAmperageB=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserAmperageB')
    RecloserAmperageC=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserAmperageC')
    RecloserAmperageGround=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserAmperageGround')
    RecloserMaxDemandA=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserMaxDemandA')
    RecloserMaxDemandB=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserMaxDemandB')
    RecloserMaxDemandC=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserMaxDemandC')
    RecloserMaxDemandGround=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserMaxDemandGround')
    RecloserOperationSummaryA=COOPGIS_FormMisc.FormGetInteger(form, 'RecloserOperationSummaryA')
    RecloserOperationSummaryB=COOPGIS_FormMisc.FormGetInteger(form, 'RecloserOperationSummaryB')
    RecloserOperationSummaryC=COOPGIS_FormMisc.FormGetInteger(form, 'RecloserOperationSummaryC')
    RecloserTargetA=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserTargetA')
    RecloserTargetB=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserTargetB')
    RecloserTargetC=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserTargetC')
    RecloserTargetGround=COOPGIS_FormMisc.FormGetFloat(form, 'RecloserTargetGround')
    RegulatorDragHandPositionMinimum=COOPGIS_FormMisc.FormGetFloat(form, 'RegulatorDragHandPositionMinimum')
    RegulatorDragHandPositionCurrent=COOPGIS_FormMisc.FormGetFloat(form, 'RegulatorDragHandPositionCurrent')
    RegulatorDragHandPositionMaximum=COOPGIS_FormMisc.FormGetFloat(form, 'RegulatorDragHandPositionMaximum')
    RegulatorVoltHigh=COOPGIS_FormMisc.FormGetFloat(form, 'RegulatorVoltHigh')
    RegulatorVoltLow=COOPGIS_FormMisc.FormGetFloat(form, 'RegulatorVoltLow')
    RegulatorVoltCurrent=COOPGIS_FormMisc.FormGetFloat(form, 'RegulatorVoltCurrent')
    RegulatorMaxAmp=COOPGIS_FormMisc.FormGetFloat(form, 'RegulatorMaxAmp')
    SurgeProtectorVisual=COOPGIS_FormMisc.FormGetObjectFromid(form, 'SurgeProtectorVisual', SubstationInspectionChoice)
    if(SurgeProtectorVisual):
        SurgeProtectorVisualid, SurgeProtectorVisualIndexWhenReverseSorted=SurgeProtectorVisual.GetCommandidData()
    else:
        SurgeProtectorVisualid, SurgeProtectorVisualIndexWhenReverseSorted = (-1,-1)
    TransformerOilLeak=COOPGIS_FormMisc.FormGetObjectFromid(form, 'TransformerOilLeak', SubstationInspectionChoice)
    if(TransformerOilLeak):
        TransformerOilLeakid, TransformerOilLeakIndexWhenReverseSorted=TransformerOilLeak.GetCommandidData()
    else:
        TransformerOilLeakid, TransformerOilLeakIndexWhenReverseSorted = (-1,-1)
    TransformerOilLevel=COOPGIS_FormMisc.FormGetObjectFromid(form, 'TransformerOilLevel', SubstationInspectionChoice)
    if(TransformerOilLevel):
        TransformerOilLevelid, TransformerOilLevelIndexWhenReverseSorted=TransformerOilLevel.GetCommandidData()
    else:
        TransformerOilLevelid, TransformerOilLevelIndexWhenReverseSorted = (-1,-1)
    TransformerOilTemperatureCurrent=COOPGIS_FormMisc.FormGetFloat(form, 'TransformerOilTemperatureCurrent')
    TransformerOilTemperatureMaximum=COOPGIS_FormMisc.FormGetFloat(form, 'TransformerOilTemperatureMaximum')
    TransformerNitrogenPressure=COOPGIS_FormMisc.FormGetFloat(form, 'TransformerNitrogenPressure')
    TransformerOilVisual=COOPGIS_FormMisc.FormGetObjectFromid(form, 'TransformerOilVisual', SubstationInspectionChoice)
    if(TransformerOilVisual):
        TransformerOilVisualid, TransformerOilVisualIndexWhenReverseSorted=TransformerOilVisual.GetCommandidData()
    else:
        TransformerOilVisualid, TransformerOilVisualIndexWhenReverseSorted = (-1,-1)
    TransformerWindingTemperatureCurrent=COOPGIS_FormMisc.FormGetFloat(form, 'TransformerWindingTemperatureCurrent')
    TransformerWindingTemperatureMaximum=COOPGIS_FormMisc.FormGetFloat(form, 'TransformerWindingTemperatureMaximum')
    MechanismCharge=COOPGIS_FormMisc.FormGetObjectFromid(form, 'MechanismCharge', SubstationInspectionChoice)
    if(MechanismCharge):
        MechanismChargeid, MechanismChargeIndexWhenReverseSorted=MechanismCharge.GetCommandidData()
    else:
        MechanismChargeid, MechanismChargeIndexWhenReverseSorted=(-1,-1)
    OperationCounter=COOPGIS_FormMisc.FormGetInteger(form, 'OperationCounter')
    
    FanWorkingVisual=COOPGIS_FormMisc.FormGetObjectFromid(form, 'FanWorkingVisual', SubstationInspectionChoice)
    if(FanWorkingVisual):
        FanWorkingVisualid, FanWorkingVisualIndexWhenReverseSorted=FanWorkingVisual.GetCommandidData()
    else:
        FanWorkingVisualid, FanWorkingVisualIndexWhenReverseSorted=(-1,-1)
    DemandAmpA=COOPGIS_FormMisc.FormGetFloat(form, 'DemandAmpA')
    DemandAmpB=COOPGIS_FormMisc.FormGetFloat(form, 'DemandAmpB')
    DemandAmpC=COOPGIS_FormMisc.FormGetFloat(form, 'DemandAmpC')
    OverCurrentTrip=COOPGIS_FormMisc.FormGetFloat(form, 'OverCurrentTrip')
    BreakerCounter=COOPGIS_FormMisc.FormGetInteger(form, 'BreakerCounter')
    command=Command()    
    DateTime=str(datetime.datetime.now())

    if(NewIndicator):
        command=command.Create(Name='CreateSubstationEquipmentInspection', 
                               CreateDateTime=DateTime, CreateUserName=UserName, Description=Description, BatteryTestid=BatteryTestid,
                               BatteryTestIndexWhenReverseSorted=BatteryTestIndexWhenReverseSorted, BatteryCharge=BatteryCharge,
                               BatteryVisualid=BatteryVisualid, BatteryVisualIndexWhenReverseSorted=BatteryVisualIndexWhenReverseSorted,
                               BatteryVoltageTest=BatteryVoltageTest, BatteryVoltageNormal=BatteryVoltageNormal, Groundid=Groundid, 
                               GroundIndexWhenReverseSorted=GroundIndexWhenReverseSorted, Visualid=Visualid,
                               VisualIndexWhenReverseSorted=VisualIndexWhenReverseSorted, 
                               MeterKWH=MeterKWH, MeterKW=MeterKW, MeterVisualid=MeterVisualid, MeterVisualIndexWhenReverseSorted=MeterVisualIndexWhenReverseSorted,
                               RecloserAmperageA=RecloserAmperageA, RecloserAmperageB=RecloserAmperageB, RecloserAmperageC=RecloserAmperageC,
                               RecloserAmperageGround=RecloserAmperageGround, RecloserMaxDemandA=RecloserMaxDemandA, RecloserMaxDemandB=RecloserMaxDemandB,
                               RecloserMaxDemandC=RecloserMaxDemandC, RecloserMaxDemandGround=RecloserMaxDemandGround, 
                               RecloserOperationSummaryA=RecloserOperationSummaryA, RecloserOperationSummaryB=RecloserOperationSummaryB, 
                               RecloserOperationSummaryC=RecloserOperationSummaryC, RecloserTargetA=RecloserTargetA, RecloserTargetB=RecloserTargetB,
                               RecloserTargetC=RecloserTargetC, RecloserTargetGround=RecloserTargetGround, 
                               RegulatorDragHandPositionMinimum=RegulatorDragHandPositionMinimum, RegulatorDragHandPositionCurrent=RegulatorDragHandPositionCurrent,
                               RegulatorDragHandPositionMaximum=RegulatorDragHandPositionMaximum,
                               RegulatorVoltHigh=RegulatorVoltHigh,
                               RegulatorVoltLow=RegulatorVoltLow, RegulatorVoltCurrent=RegulatorVoltCurrent, RegulatorMaxAmp=RegulatorMaxAmp, 
                               SurgeProtectorVisualid=SurgeProtectorVisualid, 
                               SurgeProtectorVisualIndexWhenReverseSorted=SurgeProtectorVisualIndexWhenReverseSorted, 
                               TransformerOilLeakid=TransformerOilLeakid, TransformerOilLeakIndexWhenReverseSorted=TransformerOilLeakIndexWhenReverseSorted,
                               TransformerOilLevelid=TransformerOilLevelid, TransformerOilLevelIndexWhenReverseSorted=TransformerOilLevelIndexWhenReverseSorted,
                               TransformerOilTemperatureCurrent=TransformerOilTemperatureCurrent, TransformerOilTemperatureMaximum=TransformerOilTemperatureMaximum, 
                               TransformerNitrogenPressure=TransformerNitrogenPressure,
                               TransformerOilVisualid=TransformerOilVisualid, TransformerOilVisualIndexWhenReverseSorted=TransformerOilVisualIndexWhenReverseSorted,
                               TransformerWindingTemperatureCurrent=TransformerWindingTemperatureCurrent, 
                               TransformerWindingTemperatureMaximum=TransformerWindingTemperatureMaximum, 
                               MechanismChargeid=MechanismChargeid, MechanismChargeIndexWhenReverseSorted=MechanismChargeIndexWhenReverseSorted,
                               OperationCounter=OperationCounter, FanWorkingVisualid=FanWorkingVisualid, 
                               FanWorkingVisualIndexWhenReverseSorted=FanWorkingVisualIndexWhenReverseSorted,
                               SubstationEquipmentid=SubstationEquipmentid, 
                               SubstationEquipmentIndexWhenReverseSorted=SubstationEquipmentIndexWhenReverseSorted, DateTime=DateTime, 
                               DemandAmpA=DemandAmpA, DemandAmpB=DemandAmpB, DemandAmpC=DemandAmpC,
                               OverCurrentTrip=OverCurrentTrip, BreakerCounter=BreakerCounter, CommandUserName=UserName)
        substationEquipmentInspection=command.Process()
    elif(UpdateIndicator and COOPGIS_FormMisc.FormGetInteger(form, 'SubstationEquipmentInspectionid')):
        SubstationEquipmentInspectionid=COOPGIS_FormMisc.FormGetInteger(form, 'SubstationEquipmentInspectionid')
        substationEquipmentInspection=SubstationEquipmentInspection.objects.filter(id=SubstationEquipmentInspectionid)[0]
        Objectid, ObjectIndexWhenReverseSorted=substationEquipmentInspection.GetCommandidData()
        command=command.Create(Name='EditSubstationEquipmentInspection', Objectid=Objectid, ObjectIndexWhenReverseSorted=ObjectIndexWhenReverseSorted,
                               LastModifyDateTime=DateTime, LastModifyUserName=UserName, Description=Description, BatteryTestid=BatteryTestid,
                               BatteryTestIndexWhenReverseSorted=BatteryTestIndexWhenReverseSorted, BatteryCharge=BatteryCharge,
                               BatteryVisualid=BatteryVisualid, BatteryVisualIndexWhenReverseSorted=BatteryVisualIndexWhenReverseSorted,
                               BatteryVoltageTest=BatteryVoltageTest, BatteryVoltageNormal=BatteryVoltageNormal, Groundid=Groundid, 
                               GroundIndexWhenReverseSorted=GroundIndexWhenReverseSorted, Visualid=Visualid,
                               VisualIndexWhenReverseSorted=VisualIndexWhenReverseSorted, 
                               MeterKWH=MeterKWH, MeterKW=MeterKW, MeterVisualid=MeterVisualid, MeterVisualIndexWhenReverseSorted=MeterVisualIndexWhenReverseSorted,
                               RecloserAmperageA=RecloserAmperageA, RecloserAmperageB=RecloserAmperageB, RecloserAmperageC=RecloserAmperageC,
                               RecloserAmperageGround=RecloserAmperageGround, RecloserMaxDemandA=RecloserMaxDemandA, RecloserMaxDemandB=RecloserMaxDemandB,
                               RecloserMaxDemandC=RecloserMaxDemandC, RecloserMaxDemandGround=RecloserMaxDemandGround, 
                               RecloserOperationSummaryA=RecloserOperationSummaryA, RecloserOperationSummaryB=RecloserOperationSummaryB, 
                               RecloserOperationSummaryC=RecloserOperationSummaryC, RecloserTargetA=RecloserTargetA, RecloserTargetB=RecloserTargetB,
                               RecloserTargetC=RecloserTargetC, RecloserTargetGround=RecloserTargetGround, 
                               RegulatorDragHandPositionMinimum=RegulatorDragHandPositionMinimum, RegulatorDragHandPositionCurrent=RegulatorDragHandPositionCurrent,
                               RegulatorDragHandPositionMaximum=RegulatorDragHandPositionMaximum,
                               RegulatorVoltHigh=RegulatorVoltHigh,
                               RegulatorVoltLow=RegulatorVoltLow, RegulatorVoltCurrent=RegulatorVoltCurrent, RegulatorMaxAmp=RegulatorMaxAmp, 
                               SurgeProtectorVisualid=SurgeProtectorVisualid, 
                               SurgeProtectorVisualIndexWhenReverseSorted=SurgeProtectorVisualIndexWhenReverseSorted, 
                               TransformerOilLeakid=TransformerOilLeakid, TransformerOilLeakIndexWhenReverseSorted=TransformerOilLeakIndexWhenReverseSorted,
                               TransformerOilLevelid=TransformerOilLevelid, TransformerOilLevelIndexWhenReverseSorted=TransformerOilLevelIndexWhenReverseSorted,
                               TransformerOilTemperatureCurrent=TransformerOilTemperatureCurrent, TransformerOilTemperatureMaximum=TransformerOilTemperatureMaximum, 
                               TransformerNitrogenPressure=TransformerNitrogenPressure,
                               TransformerOilVisualid=TransformerOilVisualid, TransformerOilVisualIndexWhenReverseSorted=TransformerOilVisualIndexWhenReverseSorted,
                               TransformerWindingTemperatureCurrent=TransformerWindingTemperatureCurrent, 
                               TransformerWindingTemperatureMaximum=TransformerWindingTemperatureMaximum, 
                               MechanismChargeid=MechanismChargeid, MechanismChargeIndexWhenReverseSorted=MechanismChargeIndexWhenReverseSorted,
                               OperationCounter=OperationCounter, FanWorkingVisualid=FanWorkingVisualid, 
                               FanWorkingVisualIndexWhenReverseSorted=FanWorkingVisualIndexWhenReverseSorted,
                               DemandAmpA=DemandAmpA, DemandAmpB=DemandAmpB, DemandAmpC=DemandAmpC,
                               OverCurrentTrip=OverCurrentTrip, BreakerCounter=BreakerCounter,
                               SubstationEquipmentid=SubstationEquipmentid, 
                               SubstationEquipmentIndexWhenReverseSorted=SubstationEquipmentIndexWhenReverseSorted, DateTime=DateTime, CommandUserName=UserName)
        substationEquipmentInspection=command.Process() 
    return substationEquipmentInspection







def PopulateSubstationEquipmentInspectionForm(form, substationEquipmentInspection):
    form.data['UpdateIndicator']=False
    form.data['NewIndicator']=False
    if(substationEquipmentInspection):
        form.data['SubstationEquipmentInspectionSelection']=substationEquipmentInspection.id
        form.data['SubstationEquipmentInspectionid']=substationEquipmentInspection.id
        form.data['Description']=substationEquipmentInspection.Description
        form.data['CreateDateTime']=substationEquipmentInspection.CreateDateTime
        form.data['CreateUserName']=substationEquipmentInspection.CreateUserName    
        form.data['LastModifyDateTime']=substationEquipmentInspection.LastModifyDateTime
        form.data['LastModifyUserName']=substationEquipmentInspection.LastModifyUserName
        if(substationEquipmentInspection.BatteryTest):
            form.setData({'BatteryTest': substationEquipmentInspection.BatteryTest.id})
        else:
            form.setData({'BatteryTest': -1})
        form.data['BatteryCharge']=substationEquipmentInspection.BatteryCharge
        if(substationEquipmentInspection.BatteryVisual):
            form.setData({'BatteryVisual': substationEquipmentInspection.BatteryVisual.id})
        else:
            form.setData({'BatteryVisual': -1})
        form.data['BatteryVoltageTest']=substationEquipmentInspection.BatteryVoltageTest
        form.data['BatteryVoltageNormal']=substationEquipmentInspection.BatteryVoltageNormal
        if(substationEquipmentInspection.Ground):
            form.setData({'Ground': substationEquipmentInspection.Ground.id})
        else:
            form.setData({'Ground': -1})
        if(substationEquipmentInspection.Visual):
            form.setData({'Visual': substationEquipmentInspection.Visual.id})
        else:
            form.setData({'Visual': -1})
        form.data['MeterKWH']=substationEquipmentInspection.MeterKWH
        form.data['MeterKW']=substationEquipmentInspection.MeterKW
        if(substationEquipmentInspection.MeterVisual):
            form.setData({'MeterVisual': substationEquipmentInspection.MeterVisual.id})
        else:
            form.setData({'MeterVisual': -1})
        form.data['RecloserAmperageA']=substationEquipmentInspection.RecloserAmperageA
        form.data['RecloserAmperageB']=substationEquipmentInspection.RecloserAmperageB
        form.data['RecloserAmperageC']=substationEquipmentInspection.RecloserAmperageC
        form.data['RecloserAmperageGround']=substationEquipmentInspection.RecloserAmperageGround
        form.data['RecloserMaxDemandA']=substationEquipmentInspection.RecloserMaxDemandA
        form.data['RecloserMaxDemandB']=substationEquipmentInspection.RecloserMaxDemandB
        form.data['RecloserMaxDemandC']=substationEquipmentInspection.RecloserMaxDemandC
        form.data['RecloserMaxDemandGround']=substationEquipmentInspection.RecloserMaxDemandGround
        form.data['RecloserOperationSummaryA']=substationEquipmentInspection.RecloserOperationSummaryA
        form.data['RecloserOperationSummaryB']=substationEquipmentInspection.RecloserOperationSummaryB
        form.data['RecloserOperationSummaryC']=substationEquipmentInspection.RecloserOperationSummaryC
        form.data['RecloserTargetA']=substationEquipmentInspection.RecloserTargetA
        form.data['RecloserTargetB']=substationEquipmentInspection.RecloserTargetB
        form.data['RecloserTargetC']=substationEquipmentInspection.RecloserTargetC
        form.data['RecloserTargetGround']=substationEquipmentInspection.RecloserTargetGround
        form.data['RegulatorDragHandPositionMinimum']=substationEquipmentInspection.RegulatorDragHandPositionMinimum
        form.data['RegulatorDragHandPositionCurrent']=substationEquipmentInspection.RegulatorDragHandPositionCurrent
        form.data['RegulatorDragHandPositionMaximum']=substationEquipmentInspection.RegulatorDragHandPositionMaximum
        form.data['RegulatorVoltHigh']=substationEquipmentInspection.RegulatorVoltHigh
        form.data['RegulatorVoltLow']=substationEquipmentInspection.RegulatorVoltLow
        form.data['RegulatorVoltCurrent']=substationEquipmentInspection.RegulatorVoltCurrent
        form.data['RegulatorMaxAmp']=substationEquipmentInspection.RegulatorMaxAmp
        if(substationEquipmentInspection.SurgeProtectorVisual):
            form.setData({'SurgeProtectorVisual': substationEquipmentInspection.SurgeProtectorVisual.id})
        else:
            form.setData({'SurgeProtectorVisual': -1})
        if(substationEquipmentInspection.TransformerOilLeak):
            form.setData({'TransformerOilLeak': substationEquipmentInspection.TransformerOilLeak.id})
        else:
            form.setData({'TransformerOilLeak': -1})
        if(substationEquipmentInspection.TransformerOilLevel):
            form.setData({'TransformerOilLevel': substationEquipmentInspection.TransformerOilLevel.id})
        else:
            form.setData({'TransformerOilLevel': -1})
        form.data['TransformerNitrogenPressure']=substationEquipmentInspection.TransformerNitrogenPressure
        if(substationEquipmentInspection.TransformerOilVisual):
            form.setData({'TransformerOilVisual': substationEquipmentInspection.TransformerOilVisual.id})
        else:
            form.setData({'TransformerOilVisual': -1})
        form.data['TransformerOilTemperatureMaximum']=substationEquipmentInspection.TransformerOilTemperatureMaximum
        form.data['TransformerOilTemperatureCurrent']=substationEquipmentInspection.TransformerOilTemperatureCurrent
        form.data['TransformerWindingTemperatureMaximum']=substationEquipmentInspection.TransformerWindingTemperatureMaximum
        form.data['TransformerWindingTemperatureCurrent']=substationEquipmentInspection.TransformerWindingTemperatureCurrent
        if(substationEquipmentInspection.MechanismCharge):
            form.setData({'MechanismCharge': substationEquipmentInspection.MechanismCharge.id})
        else:
            form.setData({'MechanismCharge': -1})
        form.data['OperationCounter']=substationEquipmentInspection.OperationCounter
        form.data['DemandAmpA']=substationEquipmentInspection.DemandAmpA
        form.data['DemandAmpB']=substationEquipmentInspection.DemandAmpB
        form.data['DemandAmpC']=substationEquipmentInspection.DemandAmpC
        form.data['OverCurrentTrip']=substationEquipmentInspection.OverCurrentTrip
        form.data['BreakerCounter']=substationEquipmentInspection.BreakerCounter
    else:
        form.data['SubstationEquipmentInspectionSelection']=''
        form.data['SubstationEquipmentInspectionid']=''
        form.data['Description']=''
        form.data['CreateDateTime']=''
        form.data['CreateUserName']=''    
        form.data['LastModifyDateTime']=''
        form.data['LastModifyUserName']=''
        form.setData({'BatteryTest': -1})
        form.data['BatteryCharge']=''
        form.setData({'BatteryVisual': -1})
        form.data['BatteryVoltageTest']=''
        form.data['BatteryVoltageNormal']=''
        form.setData({'Ground': -1})
        form.setData({'Visual': -1})
        form.data['MeterKWH']=''
        form.data['MeterKW']=''
        form.setData({'MeterVisual': -1})
        form.data['RecloserAmperageA']=''
        form.data['RecloserAmperageB']=''
        form.data['RecloserAmperageC']=''
        form.data['RecloserAmperageGround']=''
        form.data['RecloserMaxDemandA']=''
        form.data['RecloserMaxDemandB']=''
        form.data['RecloserMaxDemandC']=''
        form.data['RecloserMaxDemandGround']=''
        form.data['RecloserOperationSummaryA']=''
        form.data['RecloserOperationSummaryB']=''
        form.data['RecloserOperationSummaryC']=''
        form.data['RecloserTargetA']=''
        form.data['RecloserTargetB']=''
        form.data['RecloserTargetC']=''
        form.data['RecloserTargetGround']=''
        form.data['RegulatorDragHandPositionMinimum']=''
        form.data['RegulatorDragHandPositionCurrent']=''
        form.data['RegulatorDragHandPositionMaximum']=''
        form.data['RegulatorVoltHigh']=''
        form.data['RegulatorVoltLow']=''
        form.data['RegulatorVoltCurrent']=''
        form.data['RegulatorMaxAmp']=''
        form.setData({'SurgeProtectorVisual': -1})
        form.setData({'TransformerOilLeak': -1})
        form.setData({'TransformerOilLevel': -1})  
        form.setData({'TransformerNitrogenPressure': ''})
        form.setData({'TransformerOilVisual': -1})
        form.data['TransformerOilTemperatureMaximum']=''
        form.data['TransformerOilTemperatureCurrent']=''
        form.data['TransformerWindingTemperatureMaximum']=''
        form.data['TransformerWindingTemperatureCurrent']=''
        form.setData({'MechanismCharge': -1})
        form.data['OperationCounter']=''
        form.data['DemandAmpA']=''
        form.data['DemandAmpB']=''
        form.data['DemandAmpC']=''
        form.data['OverCurrentTrip']=''
        form.data['BreakerCounter']=''
    return form






def BuildSubstationEquipmentSettingForm(substationEquipmentSetting):
    from django.contrib import admin
    Dict={}
    SubstationEquipmentSettingChoices=GetSubstationEquipmentSettingChoices(substationEquipmentSetting)
    Dict['SubstationEquipmentSettingSelection']=forms.ChoiceField(SubstationEquipmentSettingChoices, required=False)
    if(not substationEquipmentSetting):
        substationEquipmentSetting=SubstationEquipmentSetting()
    Dict['SubstationEquipmentSettingid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5', 'READONLY':'True'}))    
    Dict['Name']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['Description']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    #Action Fields
    Dict['UpdateIndicator']=forms.BooleanField(required=False)
    Dict['NewIndicator']=forms.BooleanField(required=False)
    return Dict

def ProcessSubstationEquipmentSettingForm(form, UserName):
    import models
    UpdateIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateIndicator')
    NewIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NewIndicator')
    Description=COOPGIS_FormMisc.FormGetString(form, 'Description')
    Name=COOPGIS_FormMisc.FormGetString(form, 'Name')
    SubstationEquipmentSettingid=COOPGIS_FormMisc.FormGetInteger(form, 'SubstationEquipmentSettingSelection')
    try:
        substationEquipmentSetting=SubstationEquipmentSetting.objects.filter(id=SubstationEquipmentSettingid)[0]
    except:
        substationEquipmentSetting=None
    command=Command()    
    if(NewIndicator):
        command=command.Create(Name='CreateSubstationEquipmentSetting', ObjectName=Name, Description=Description, CommandUserName=UserName)
        substationEquipmentSetting=command.Process()
    elif(UpdateIndicator and COOPGIS_FormMisc.FormGetInteger(form, 'SubstationEquipmentSettingid')):
        SubstationEquipmentSettingid=COOPGIS_FormMisc.FormGetInteger(form, 'SubstationEquipmentSettingid')
        substationEquipmentSetting=SubstationEquipmentSetting.objects.filter(id=SubstationEquipmentSettingid)[0]
        Objectid, ObjectIndexWhenReverseSorted=substationEquipmentSetting.GetCommandidData()
        command=command.Create(Name='EditSubstationEquipmentSetting', Objectid=Objectid, ObjectIndexWhenReverseSorted=ObjectIndexWhenReverseSorted,
                               ObjectName=Name, Description=Description, CommandUserName=UserName)
        substationEquipmentSetting=command.Process()
    return substationEquipmentSetting

def PopulateSubstationEquipmentSettingForm(form, substationEquipmentSetting):
    form.data['UpdateIndicator']=False
    form.data['NewIndicator']=False
    if(substationEquipmentSetting):
        form.data['SubstationEquipmentSettingid']=substationEquipmentSetting.id
        form.data['Name']=substationEquipmentSetting.Name
        form.data['Description']=substationEquipmentSetting.Description
    else:
        form.data['SubstationEquipmentSettingid']=''
        form.data['Name']=''
        form.data['Description']=''
    return form

def BuildSubstationCircuitForm(substationCircuit):
    from django.contrib import admin
    Dict={}
    SubstationCircuitChoices=GetSubstationCircuitChoices(substationCircuit)
    if(substationCircuit):
        substation=substationCircuit.Substation
    else:
        substation=None
    Dict['Substation']=forms.ChoiceField(GetSubstationChoices(substation), required=False)
    Dict['SubstationCircuitSelection']=forms.ChoiceField(SubstationCircuitChoices, required=False)
    if(not substationCircuit):
        substationCircuit=SubstationCircuit()
    Dict['SubstationCircuitid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5', 'READONLY':'True'}))    
    Dict['Name']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'20'}))
    Dict['Description']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'20'}))
    Dict['CircuitNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'20'}))
    Dict['AMRCircuitName']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['AMRSubstationIdentifier']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['AMRBusIdentifier']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['AMRFeederIdentifier']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))

    #Action Fields
    Dict['UpdateIndicator']=forms.BooleanField(required=False)
    Dict['NewIndicator']=forms.BooleanField(required=False)
    return Dict

def ProcessSubstationCircuitForm(form, UserName):
    import models
    UpdateIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateIndicator')
    NewIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NewIndicator')
    Description=COOPGIS_FormMisc.FormGetString(form, 'Description')
    Name=COOPGIS_FormMisc.FormGetString(form, 'Name')
    CircuitNumber=COOPGIS_FormMisc.FormGetInteger(form, 'CircuitNumber')
    AMRCircuitName=COOPGIS_FormMisc.FormGetString(form, 'AMRCircuitName')
    AMRSubstationIdentifier=COOPGIS_FormMisc.FormGetInteger(form, 'AMRSubstationIdentifier')
    AMRBusIdentifier=COOPGIS_FormMisc.FormGetInteger(form, 'AMRBusIdentifier')
    AMRFeederIdentifier=COOPGIS_FormMisc.FormGetInteger(form, 'AMRFeederIdentifier')

    substation=COOPGIS_FormMisc.FormGetObjectFromid(form, 'Substation', Substation)
    if(substation):
        Substationid, SubstationIndexWhenReverseSorted=substation.GetCommandidData()
    else:
        Substationid, SubstationIndexWhenReverseSorted= (-1,-1)
    command=Command()

    SubstationCircuitid=COOPGIS_FormMisc.FormGetInteger(form, 'SubstationCircuitSelection')
    try:
        substationCircuit=SubstationCircuit.objects.filter(id=SubstationCircuitid)[0]
    except:
        substationCircuit=None
    if(NewIndicator):
        command=command.Create(Name='CreateSubstationCircuit', Description=Description, Substationid=Substationid, 
                               AMRCircuitName=AMRCircuitName, AMRSubstationIdentifier=AMRSubstationIdentifier, 
                               AMRBusIdentifier=AMRBusIdentifier, AMRFeederIdentifier=AMRFeederIdentifier,
                               SubstationIndexWhenReverseSorted=SubstationIndexWhenReverseSorted, ObjectName=Name, CircuitNumber=CircuitNumber,
                               CommandUserName=UserName)
        substationCircuit=command.Process()
    elif(UpdateIndicator and COOPGIS_FormMisc.FormGetInteger(form, 'SubstationCircuitid')):
        substationCircuit=COOPGIS_FormMisc.FormGetObjectFromid(form, 'SubstationCircuitid', SubstationCircuit)
        if(substationCircuit):
            SubstationCircuitid, SubstationCircuitIndexWhenReverseSorted=substationCircuit.GetCommandidData()
        else:
            SubstationCircuitid, SubstationCircuitIndexWhenReverseSorted= (-1,-1)
        command=command.Create(Name='EditSubstationCircuit', Objectid=SubstationCircuitid, ObjectIndexWhenReverseSorted=SubstationCircuitIndexWhenReverseSorted, 
                               AMRCircuitName=AMRCircuitName, AMRSubstationIdentifier=AMRSubstationIdentifier, 
                               AMRBusIdentifier=AMRBusIdentifier, AMRFeederIdentifier=AMRFeederIdentifier,
                               Description=Description, Substationid=Substationid, 
                               SubstationIndexWhenReverseSorted=SubstationIndexWhenReverseSorted, ObjectName=Name, CircuitNumber=CircuitNumber,
                               CommandUserName=UserName)
        substationCircuit=command.Process()
    return substationCircuit

def PopulateSubstationCircuitForm(form, substationCircuit):
    form.data['UpdateIndicator']=False
    form.data['NewIndicator']=False
    if(substationCircuit):
        form.data['Name']=substationCircuit.Name
        form.data['SubstationCircuitid']=substationCircuit.id
        form.data['CircuitNumber']=substationCircuit.CircuitNumber
        form.data['Substation']=substationCircuit.Substation.id
        form.data['Description']=substationCircuit.Description
        form.data['AMRCircuitName']=substationCircuit.AMRCircuitName
        form.data['AMRSubstationIdentifier']=substationCircuit.AMRSubstationIdentifier
        form.data['AMRBusIdentifier']=substationCircuit.AMRBusIdentifier
        form.data['AMRFeederIdentifier']=substationCircuit.AMRFeederIdentifier

    else:
        form.data['Name']=''
        form.data['SubstationCircuitid']=''
        form.data['CircuitNumber']=''
        form.data['Substation']=''
        form.data['Description']=''
        form.data['AMRCircuitName']=''
        form.data['AMRSubstationIdentifier']=''
        form.data['AMRBusIdentifier']=''
        form.data['AMRFeederIdentifier']=''

    return form






def BuildWarehouseMeterInventoryCheckInForm():
    from django.contrib import admin
    Dict={}
    WarehouseInspectionChoices=[]
    WarehouseInspectionChoices.append((-1, 'None Selected'))
    WarehouseInspectionFormChoices=WarehouseMeterInspectionChoice.objects.all().order_by('id')
    for i in WarehouseInspectionFormChoices:
        if(not [i.id, str(i)] in WarehouseInspectionChoices):
            WarehouseInspectionChoices.append([i.id, str(i)])

    Dict['WarehouseMeterInspectionChoice']=forms.ChoiceField(WarehouseInspectionChoices, required=False)
    Dict['MeterNumberCheckIn']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'25'}))
    Dict['MeterDCSINumberCheckIn']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'25'}))
    Dict['CheckOutIndicator']=forms.BooleanField(required=False)
    Dict['Description']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'25'}))
    Dict['JunkIndicator']=forms.BooleanField(required=False)
    Dict['Location']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'25'}))
    Dict['ShowAllIndicator']=forms.BooleanField(required=False)

    return Dict

def ProcessWarehouseMeterInventoryCheckInForm(form, UserName):
    import models
    MeterDCSINumberCheckIn=COOPGIS_FormMisc.FormGetString(form, 'MeterDCSINumberCheckIn')
    MeterNumberCheckIn=COOPGIS_FormMisc.FormGetString(form, 'MeterNumberCheckIn')
    Description=COOPGIS_FormMisc.FormGetString(form, 'Description')
    Location=COOPGIS_FormMisc.FormGetString(form, 'Location')
    CheckOutIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'CheckOutIndicator')
    warehouseMeterInspectionChoice=COOPGIS_FormMisc.FormGetObjectFromid(form, 'WarehouseMeterInspectionChoice', WarehouseMeterInspectionChoice)
    Now=str(datetime.datetime.now())
    if(warehouseMeterInspectionChoice):
        WarehouseMeterInspectionChoiceid, WarehouseMeterInspectionChoiceIndexWhenReverseSorted=warehouseMeterInspectionChoice.GetCommandidData()
        InspectionDateTime=Now
    else:
        WarehouseMeterInspectionChoiceid, WarehouseMeterInspectionChoiceIndexWhenReverseSorted=(-1,-1)
        InspectionDateTime=None
    JunkIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'JunkIndicator')
    if(JunkIndicator):
        JunkDateTime=Now
    else:
        JunkDateTime=None
    ShowAllIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ShowAllIndicator')

    PossibleEntries1=PossibleEntries2=None
    if(MeterDCSINumberCheckIn or MeterNumberCheckIn):
        if(MeterDCSINumberCheckIn): 
            PossibleEntries1=WarehouseMeterInventoryCheckIn.objects.filter(MeterDCSINumber=MeterDCSINumberCheckIn).filter(CheckOutDateTime__isnull=True)
        if(MeterNumberCheckIn):
            PossibleEntries2=WarehouseMeterInventoryCheckIn.objects.filter(MeterNumber=MeterNumberCheckIn).filter(CheckOutDateTime__isnull=True)
        if(PossibleEntries1):
            warehouseMeterInventoryCheckIn=PossibleEntries1[0]
        elif(PossibleEntries2):
            warehouseMeterInventoryCheckIn=PossibleEntries2[0]
        else:
            command=Command() 
            command=command.Create(Name='CreateWarehouseMeterInventoryCheckIn', MeterNumber=MeterNumberCheckIn, MeterDCSINumber=MeterDCSINumberCheckIn, 
                                   CheckInDateTime=str(Now), InspectionDateTime=InspectionDateTime, CheckOutDateTime='', Description=Description,
                                   JunkIndicator=JunkIndicator, JunkDateTime=JunkDateTime, 
                                   WarehouseMeterInspectionChoiceid=WarehouseMeterInspectionChoiceid, 
                                   WarehouseMeterInspectionChoiceIndexWhenReverseSorted=WarehouseMeterInspectionChoiceIndexWhenReverseSorted,
                                   Location=Location, CommandUserName=UserName)
            command.Process()
            return form, ShowAllIndicator
    else:
        return form, ShowAllIndicator
    #if here, there is a warehouseMeterInventoryCheckIn instance that needs to be checked out or modified
    Objectid, ObjectIndexWhenReverseSorted=warehouseMeterInventoryCheckIn.GetCommandidData()
    if(not MeterDCSINumberCheckIn):
        MeterDCSINumberCheckIn=warehouseMeterInventoryCheckIn.MeterDCSINumber
    if(not MeterNumberCheckIn):
        MeterNumberCheckIn=warehouseMeterInventoryCheckIn.MeterNumber
    if(not Description):
        Description=warehouseMeterInventoryCheckIn.Description
    if(not Location):
        Location=warehouseMeterInventoryCheckIn.Location
    if(WarehouseMeterInspectionChoiceid == -1):
        if(warehouseMeterInventoryCheckIn.WarehouseMeterInspectionChoice):
            WarehouseMeterInspectionChoiceid, WarehouseMeterInspectionChoiceIndexWhenReverseSorted=warehouseMeterInventoryCheckIn.WarehouseMeterInspectionChoice.GetCommandidData()
            InspectionDateTime=warehouseMeterInventoryCheckIn.InspectionDateTime
        else:
            InspectionDateTime=''
    else:
        InspectionDateTime=str(Now)
    if(CheckOutIndicator):
        CheckOutDateTime=str(Now)
    else:
        CheckOutDateTime=''
    command=Command()
    command=command.Create(Name='EditWarehouseMeterInventoryCheckIn', Objectid=Objectid, ObjectIndexWhenReverseSorted=ObjectIndexWhenReverseSorted,
                           MeterDCSINumber=MeterDCSINumberCheckIn, MeterNumber=MeterNumberCheckIn,
                           CheckInDateTime=warehouseMeterInventoryCheckIn.CheckInDateTime, 
                           InspectionDateTime=InspectionDateTime, Location=Location, 
                           CheckOutDateTime=CheckOutDateTime, Description=Description, JunkIndicator=JunkIndicator, JunkDateTime=JunkDateTime, 
                           WarehouseMeterInspectionChoiceid=WarehouseMeterInspectionChoiceid, 
                           WarehouseMeterInspectionChoiceIndexWhenReverseSorted=WarehouseMeterInspectionChoiceIndexWhenReverseSorted,
                           CommandUserName=UserName)
    command.Process()
    return form, ShowAllIndicator

def PopulateWarehouseMeterInventoryCheckInForm(form):
    form.setData({'WarehouseMeterInspectionChoice': -1})
    form.data['MeterNumberCheckIn']=''
    form.data['MeterDCSINumberCheckIn']=''
    form.data['CheckOutIndicator']=''
    form.data['Description']=''
    form.data['Location']=''
    form.data['JunkIndicator']=''
    return form







def BuildWarehouseMeterInspectionChoiceForm():
    from django.contrib import admin
    Dict={}
    #Build Inspection Choices List
    InspectionChoices=[]
    EndOfListChoices=[]
    WarehouseMeterInspectionChoices=WarehouseMeterInspectionChoice.objects.all().order_by('Name')
    for i in WarehouseMeterInspectionChoices:
        if(i.ActiveIndicator):
            InspectionChoices.append([i.id, str(i)])
        else:
            EndOfListChoices.append([i.id, 'INACTIVE:  ' + str(i)])
    for i in EndOfListChoices:
        InspectionChoices.append(i)
    Dict['Inspections']=forms.ChoiceField(InspectionChoices, required=False)
    #WarehouseMeterInspectionChoice Attribute Fields
    Dict['Name']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['Description']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['WarehouseMeterInspectionChoiceid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5', 'READONLY':'True'}))    
    Dict['ActiveIndicator']=forms.BooleanField(required=False)
    #Action Fields
    Dict['UpdateIndicator']=forms.BooleanField(required=False)
    Dict['NewIndicator']=forms.BooleanField(required=False)    
    return Dict

def ProcessWarehouseMeterInspectionChoiceForm(form, UserName):
    import models
    UpdateIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateIndicator')
    NewIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NewIndicator')
    ActiveIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ActiveIndicator')
    Name=COOPGIS_FormMisc.FormGetString(form, 'Name')
    Description=COOPGIS_FormMisc.FormGetString(form, 'Description')
    WarehouseMeterInspectionChoiceid=COOPGIS_FormMisc.FormGetInteger(form, 'Inspections', 0)
    try:
        warehouseMeterInspectionChoice=WarehouseMeterInspectionChoice.objects.filter(id=WarehouseMeterInspectionChoiceid)[0]
    except:
        warehouseMeterInspectionChoice=None
    
    command=Command()    
    if(NewIndicator):
        command=command.Create(Name='CreateWarehouseMeterInspectionChoice', ObjectName=Name, Description=Description, ActiveIndicator=ActiveIndicator,
                               CommandUserName=UserName)
        warehouseMeterInspectionChoice=command.Process()
    elif(UpdateIndicator and warehouseMeterInspectionChoice):
        Objectid, ObjectIndexWhenReverseSorted=warehouseMeterInspectionChoice.GetCommandidData()
        command=command.Create(Name='EditWarehouseMeterInspectionChoice', Objectid=warehouseMeterInspectionChoice.id, ObjectName=Name,
                               Description=Description, ActiveIndicator=ActiveIndicator, CommandUserName=UserName)
        command.Process()
    return warehouseMeterInspectionChoice



def PopulateWarehouseMeterInspectionChoiceForm(form, warehouseMeterInspectionChoice):
    form.data['UpdateIndicator']=False
    form.data['NewIndicator']=False
    if(warehouseMeterInspectionChoice):
        form.data['Name']=warehouseMeterInspectionChoice.Name
        form.data['WarehouseMeterInspectionChoiceid']=warehouseMeterInspectionChoice.id
        form.data['Description']=warehouseMeterInspectionChoice.Description
    else:
        form.data['Name']=''
        form.data['WarehouseMeterInspectionChoiceid']=''
        form.data['Description']=''
    return form




